0

我已经在 Hexo 中设置了我的帖子,并为每个帖子分配了标签。但是标题标签并没有按照我想要的方式大写。

这是呈现的 HTML:

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

但我会做到这一点:

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

标签:pizza 是小写的,不知道如何使标签在标题标签中以大写字母开头(例如 Pizza、Pasta、Italy 等)。

我的代码:

<%
    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>

提前致谢!

4

2 回答 2

0

这是一个将句子的每个单词大写的函数:

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(' ');
}

在您的代码中:

<%
    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>
于 2016-08-26T13:12:20.363 回答
0

我不知道这是否是 hexo 中的新功能,但如果您还在寻找,有titlecase,这是您可以在模板中使用的功能。

这现在应该随您的 hexo 安装一起提供。如果您将ejs其用作渲染器,则可以按照文档所述使用它:

你可以做得到<%- titlecase('pizza') %>你想要的。

如果您需要编写自己的函数,首选方法是将它们写入/scripts/my_helpers.js文件中(将 .js 文件命名为您想要的任何名称,但它必须scripts在您的项目目录中)。或者,发布带有前缀的模块hexo-并将其导入您的项目(如果您这样做,请确保它在 package.json 中列出)。

然后,您可以在 .js 文件中使用以下咒语使您的 javascript 函数可用:

// note, I haven't tested this code.
hexo.extend.helper.register('capitalize', (aString) => {
    return aString.split(" ").map(function(word) {
        return word[0].toUpperCase() + word.substring(1).toLowerCase()}).join(" ")
});

然后你可以使用<%- capitalize("i am a strInG") %>

<title>
<% if (page.title) { %>
    <%= capitalize(page.title) %> | 
<% } %>
<%= config.title %>
</title>

`

于 2017-12-11T11:03:17.030 回答