Search code examples
ejshexo

Better Hexo title tag


I have setup my posts in Hexo and assigned tags to each post. However the title tag is not capitalizing the way I would like.

This is the rendered HTML:

<title>Viewing pizza | My site</title>

But I would to achieve this:

<title>Viewing Pizza | My site</title>

The tag: pizza is lowercase, and not sure how to make the tag begin with a capital letter within the title tag (e.g. Pizza, Pasta, Italy and so on).

My code:

<%
    function capitalize (str) { return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase() }
    var title = page.title;
    if (is_archive()) {
        title = capitalize(__('Viewing'));
        if (is_month()) {
            title += ': ' + page.year + '/' + page.month;
        } else if (is_year()) {
            title += ': ' + page.year;
        }
    } else if (is_category()) {
        title = capitalize(__('Viewing')) + ': ' + page.category;
    } else if (is_tag()) {
        title = capitalize(__('Viewing')) + ': ' + page.tag;
    }
%>
<title><% if (title) { %><%= title %> | <% } %><%= config.title %></title>

Thanks in advance!


Solution

  • Here is a function to capitalize each words of a sentence :

    function capWords(str) {
        // we split string by words in an array
        // and we iterate on each word to capitalize the first letter
        // and we join each element with a space
        return str.split(' ').map(function(str) {
            return str[0].toUpperCase() + str.substr(1).toLowerCase()
        }).join(' ');
    }
    

    In your code :

    <%
        function capWords(str) {
            // we split string by words in an array
            // and we iterate on each word to capitalize the first letter
            // and we join each element with a space
            return str.split(' ').map(function(str) {
                return str[0].toUpperCase() + str.substr(1).toLowerCase()
            }).join(' ');
        }
    
        var title = page.title;
        if (is_archive()) {
            title = __('Viewing');
            if (is_month()) {
                title += ': ' + page.year + '/' + page.month;
            } else if (is_year()) {
                title += ': ' + page.year;
            }
        } else if (is_category()) {
            title = __('Viewing') + ': ' + page.category;
        } else if (is_tag()) {
            title = __('Viewing') + ': ' + page.tag;
        }
    %>
    <title>
        <% if (title) { %>
            <%= capWords(title) + ' | ' %> 
        <% } %>
        <%= config.title %>
    </title>