【问题标题】:"read more" in django postsdjango 帖子中的“阅读更多”
【发布时间】:2012-09-28 08:09:49
【问题描述】:

我正在 django/webfaction 上创建一个博客。目前我的主页显示所有帖子的所有内容。我想对其进行调整,使其仅显示每篇文章的几行,并且每篇文章都以“阅读更多”链接结尾。如何做到这一点?我是 django 和 python 的新手。请帮助我。

home.html 中的代码:

{% block content %}

  {% for post in object_list %}
  <h2>{{ post.title }} </h2>

  <div class = "post_meta">
      on {{ post.created}}
  </div>

  <div class = "post_body">
      {{ post.body|safe|linebreaks}}
  </div>

  {% endfor %}

{% endblock %}

提前致谢。

【问题讨论】:

    标签: python html django django-templates


    【解决方案1】:

    您可以使用内置模板过滤器截断doc

      <div class = "post_body">
          {{ post.body|safe|truncatewords:"50"|linebreaks }}
          <a href="{{ url_for_full_content }}">read more</a>
      </div>
    

    【讨论】:

    • 文章长度小于50字怎么办?
    • @defuz 你需要先判断内容的长度。
    • 你也可以使用 truncatechars
    • 谢谢!有效。我假设我的帖子不会少于 50 个字。
    • 如果希望其余文本显示在 div 中,而不打开另一个页面怎么办?
    【解决方案2】:

    django-model-utils扩展中可以看到字段模型SplitField的实现:

    from django.db import models
    from model_utils.fields import SplitField
    
    class Article(models.Model):
        title = models.CharField(max_length=100)
        body = SplitField()
    
    >>> a = Article.objects.all()[0]
    >>> a.body.content
    u'some text\n\n<!-- split -->\n\nmore text'
    >>> a.body.excerpt
    u'some text\n'
    >>> unicode(a.body)
    u'some text\n\n<!-- split -->\n\nmore text'
    

    它完全符合您的需要。在doc 中阅读更多内容。

    【讨论】:

    • 一种无依赖的方式是编写自己的拆分字段,但 IMO 我认为这根本不应该是模型逻辑。在这里使用自定义模板标签似乎非常好,因此这只具有代表性的好处。
    【解决方案3】:

    我知道这篇文章很旧,但这是我通过stackoverflow解决这个问题的方法......

    {% with text=post.body %}
            {% if text|wordcount > 56 %}
        <p class="half-content" id="half-{{ post.pk }}">{{text|safe|linebreaks|truncatewords:50}}<a data-id="{{ post.pk }}" href="javascript:void();" class="show-hide-btn"><br>Read more</a></p>
        <p class="full-content" id="full-{{post.pk }}" style="display: none;">{{ text|safe|linebreaks }}<a data-id="{{ post.pk}}" href="javascript:void();" class="show-hide-btn">Read less</a></p>
        {% else %}
            <p>
        {{ text|safe|linebreaks }}
        </p>
        {% endif %}
        {% endwith %}
    

    这也是您应该在模板中添加的 js 代码...

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
      $(".show-hide-btn").click(function() {
        var id = $(this).data("id");
        $("#half-" + id).toggle();//hide/show..
        $("#full-" + id).toggle();
      })
    })
    </script>
    

    【讨论】:

      【解决方案4】:
      <p  class="article-content ">{{ post.content|truncatewords:"35"|linebreaks }}</p>
      

      【讨论】:

      • 您好,欢迎您,请考虑edit您的回答添加一些额外信息。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 2011-05-21
      • 2017-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多