6

我正在 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 %}

提前致谢。

4

4 回答 4

26

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

  <div class = "post_body">
      {{ post.body|safe|truncatewords:"50"|linebreaks }}
      <a href="{{ url_for_full_content }}">read more</a>
  </div>
于 2012-10-08T05:38:01.433 回答
2

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

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'

它正确地完成了您需要的工作。在文档中阅读更多内容。

于 2012-10-08T05:38:31.757 回答
1

I know this post is old but here is how i solved this problem thanks to 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 %}

this is the js code that you should add in your template also...

<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>
于 2021-08-21T16:42:58.407 回答
0
<p  class="article-content ">{{ post.content|truncatewords:"35"|linebreaks }}</p>

于 2021-10-04T18:30:39.003 回答