【问题标题】:Obtaining the word count from a post in Jekyll for Github Pages?从 Jekyll 的帖子中获取 Github Pages 的字数?
【发布时间】:2014-10-26 21:35:56
【问题描述】:

这是我目前用来查看博客文章是否超过 120 字的代码 sn-p。如果为真,请截断内容并在帖子底部添加“阅读更多”链接。

<div class="blogs">
  {% for post in site.posts %}
    <article class="post">          
      <h3><a href="{{ site.baseurl }}/{{ site.blogs }}{{ post.title }}">{{ post.title }}</a></h3>

      {% assign wordCount = {{ post.content | size }} %}
      {% if wordCount > 120 %}
        <div class="entry">
            {{ post.content | truncatewords:120}}
        </div>

        <a href="{{ site.baseurl }}{{ post.url}}" class="read-more">Read More</a>
      {% else %}
        {{ post.content }}
      {% endif %}
    </article>
  {% endfor %}
</div>

当我提交此操作时,我收到一封来自 GitHub 的电子邮件,说构建时出现页面错误,并且没有打印出任何其他内容。

我猜这与{{ post.content }} 无法过滤掉大小有关,所以我被卡住了。

如何获取单个博客文章的字数,以便截断一些超过 120 字的文章?提前致谢。

【问题讨论】:

    标签: html github jekyll liquid github-pages


    【解决方案1】:

    {{ post.content | size }} 为您提供 post.content 字符串中的字符数。

    如果要统计字符串中的单词,请使用number_of_words 液体过滤器。

    {% assign wordCount = post.content | number_of_words %}
    

    注意:您在帖子标题{{ site.baseurl }}/{{ site.blogs }}{{ post.title }} 中有一个奇怪的链接,我认为它是{{ site.baseurl }}{{ post.url}},就像在阅读更多链接中一样。

    【讨论】:

    • 我在_config.yml 的末尾添加了带有斜线的site.blogs: blogs/,这就是为什么我以一种奇怪的方式这样做的原因。 post.url 让我很头疼,因为它在前面添加了一个额外的斜杠,Jekyll 在连接时会删除双斜杠,这会破坏 URL 链接。我现在不知道为什么,但我仍然在学习。你有什么建议吗?
    • {{ site.baseurl }}{{ post.url}} 是去这里的方式。对于帖子的自定义网址,请参阅jekyllrb.com/docs/permalinks
    【解决方案2】:

    在本地测试时,我发现{{ post.content | size }} 确实可以计算字数,因为{{ post.content }} 是一个字符串,尽管它很长。

    看到 GitHub Pages 不符合 {% if ... %} 逻辑,我猜有些东西执行不正确。没有太多信息,我被困住了。

    所以,是的,{{ post.content | size }} 确实为您提供字数统计。然而,它的条件流需要更多的测试,因为它不能正确执行。

    如果有人有更多信息,请告诉我。感谢阅读。

    【讨论】:

      【解决方案3】:
      {% for post in site.posts %}
        {% if post.content | number_of_words > 120 %}
          {{ post.content | truncatewords:120 }}
        {% endif %}
      {% endfor %}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-27
        • 2013-12-16
        • 1970-01-01
        • 2018-07-31
        • 2013-06-25
        • 2016-06-23
        • 1970-01-01
        • 2023-01-24
        相关资源
        最近更新 更多