Keats / tera

A template engine for Rust based on Jinja2/Django
http://keats.github.io/tera/
MIT License
3.54k stars 283 forks source link

Truncate cuts off image urls and html tags #785

Open that-ambuj opened 1 year ago

that-ambuj commented 1 year ago

I was trying out zola for a SSG project for a client, their stuff is written in markdown. But the main issue with Zola (most probably Tera) is that it cuts off long urls in images and closing html tags which makes the site look weird. I'm trying to render some portion of {{ page.content }} for the description of a blog item in a list, but truncate is breaking the list by not stopping at full elements in markdown or the rendered html(whichever it works on first). Below is my code.

{% for page in section.pages %}
    <li>
        <a href="{{ page.permalink | safe }}">{{ page.title }}</a>
        <div> {{ page.content | truncate(length=300) | safe }}</div>
    </li>
{% endfor %}
that-ambuj commented 1 year ago

Just tested out the same thing with Hugo, It does not have that issue and it works as expected. It counts items and text content before compiling to html, and Hence it does not cut off any html tags or urls.

Keats commented 1 year ago

Yes, truncate in Tera works at the string level and has no knowledge about HTML. I think you can do {{ page.content | striptags | truncate(length=300) | safe }}? Someone could add atruncate_html` method to Tera I guess? It depends how involved the HTML handling is of course, we don't have to have to pull in a HTML parser.

that-ambuj commented 1 year ago

The suggested workaround seems great but it is kinda complex. I would like to volunteer to add a truncate_html or a summary filter but I'm very less familiar with this project. Nonetheless, I'd like to give it a try.

PS: I think strip_tags might be problematic to img tags still. Please guide me through this one.