How do I provide a blog excerpt without having to show html code using Jinja2 Template?

╄→尐↘猪︶ㄣ 提交于 2019-12-13 15:01:59

问题


Currently I'm using jinja2 with flask and have stored a blog post using ckeditor in the database.

The data should ideally show an image first and then following the blog posts and some other images which are linked externally to flikr.

I know that I can use the {{ post.body | safe}} inside the single post view of to display the html as a real image instead of html text.

However, how do I NOT show the html but show only the text excerpt in the post in the page where there are multiple links to different prosts and excerpts without the image html showing up.

In this case "This post is dedicated to xyz" should be the excerpt

database body = column

<img alt="15189057555_7670752b57_o" class="main" src="https://farm6.staticflickr.com/5584/15189057555_7670752b57_o.jpg" style="width:100%;max-width:1920px"><p>This post is dedicated to xyz</p>

jinja2

'post' is an post object. I'm trying to limit the excerpt to 100 letters long without the html tags and images.

{{post.body[:100]}}... will show <img alt="15189057555_7670752b57_o" class="main" src="https://farm6.staticflickr.com/5584/1518905755...

The following is a code excerpt to loop through all posts to provide a link to a single blog page, a time stamp, and an excerpt of what the blog is about.

<h1>Latest Posts</h1>
{% if posts %}
    {% for post in posts%}
      <div class="post">
        <h2><a href="post/{{post.postid}}">{{post.title}}</a></h2>
        <h6>{{post.timestamp.strftime('%a %y/%m/%d')}}</h6>
        <p>{{post.body[:100]}}...</p>
        <p>Posted By: {{post.author.nickname}}</p>
      </div>
    {% endfor %}
{% else %}
    <h4>No blog posts currently</h4>
{% endif%}

Is there a better way to design this? If so, how? Please keep in mind I would like to be able to insert multiple images and text in the one blog post.

Thanks for all your help!


回答1:


You have to look at the striptags and truncate filter of Jinja http://jinja.pocoo.org/docs/dev/templates/#builtin-filters

Example:

>>> from jinja2 import Template
>>> template = Template('blogpost: {{ post|striptags }}!')
>>> template.render(post='<img alt="15189057555_7670752b57_o" class="main" src="https://farm6.staticflickr.com/5584/15189057555_7670752b57_o.jpg" style="width:100%;max-width:1920px"><p>This post is dedicated to xyz</p>') 
u'blogpost: This post is dedicated to xyz!'

In your case, you want to strip tags, and limit to 100 chars, so replace

<p>{{post.body[:100]}}...</p>

by

<p>{{post.body|striptags|truncate(100)}}</p>


来源:https://stackoverflow.com/questions/26030590/how-do-i-provide-a-blog-excerpt-without-having-to-show-html-code-using-jinja2-te

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!