Markdown and the Template Filter, Slice

by Richard 2021-10-22 18:10

I had been playing with using Markdown to enter blog entries on a Django app. One thing giving me a problem was using the filter slice with an argument of 200.

The Problem

The intention was to show the first 200 characters from each post. This works! Each post will display the first 200 characters when on the main blog page. These posts are basic blogs without styling or tags—just text.

Add tags however, and things become much more complex. HTML is sent to the browser, but if your slice includes a starting HTML tag and not a closing tag, well...suddenly everything on the page that follows the opening HTML tag was contained in it until a closing tag was reached. If I had a slice that contained <h1> for example, and no closing </h1> was included in that slice, the rest of the page following the opening tag was <h1>.

Slice was not the solution I needed. To the documentation!

The Solution

Flipping through the documentation yielded some interesting filters. Four, in particular: truncatechar, truncatechar_html, truncatewords, truncatewords_html.

The arguments are integers indicating where to truncate. The problem I was having lead me to the _html variants of the filters, as these will close HTML tags at the point of truncating. This filter will also not include HTML tags in the character count. So, where I had slice:200 in my template tags, truncatechar_html:200 was substituted.

The result: no more open HTML tags.

The resulting tag looks like this in the HTML:

{{ post.title | convert_md | truncatechars_html:200 | safe }}

Display the post.title, then use a custom filter I made for Markdown called convert_md (convert markdown to HTML), truncate the characters to 200 and close an open HTML tag (if there is one), and safe because it does not require further HTML escaping prior to output.

Go Back

Leave a comment

Comments 0