问题描述:

I would like to smartly slice an HTML content.

Taking the news as an example, the page for displaying a news list is as follows:

<table>

<tr><th>Title</th><th>Content</th></tr>

{% for news in newsList %}

<tr>

<td><a href="/news/{{news.id}}/">{{news.title}}</a></td>

<td>{{news.content | slice:":30" | safe}} ...</td>

</tr>

{% endfor %}

</table>

The content of a news is sliced such that the user will only see some part of the news. But if the place of slice:":30" happens to be in an HTML tag, there would be a problem.

For example, if the content of news.content is the following:

<p>What is Content Marketing?</p>

The result of slicing would be <p>What is Content Marketing?< ..., in which the tag <p> is not closed.

Is there any way to preserve an HTML tag when slicing?

网友答案:

I guess you should use truncatechars_html filter for this https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#truncatechars-html

相关阅读:
Top