Elegant and efficient way for Django templates?

一曲冷凌霜 提交于 2020-01-05 02:59:09

问题


I find myself ending up with template snippets in the following style:

<ul>
{% for item in items %}
<li><a class="{% if item.active %}active{% endif %}" title="{{ item.title }}" href="{{ item.get_absolute_url }}"><img src="{% thumbnail item.image 24x24 crop upscale %}" />{{ item.title|truncate_chars:30 }}</a></li>
{% endfor %}
</ul>

A while ago ai had to use a PHP framework which had some nice helpers for HTML output. I know that this cannot be directly compared, as it is not a real template-layer (rather plain PHP) - but for the idea:

<ul>
<?php foreach($items as $item) { ?> 
<li><?= HTML::anchor($item->url(), HTML::mage($item->image->url(24)), Text::limit($item->title, 30), array('title' => $item->title, 'class' => ($item->active) ? 'active' : '') ?></li>
<?php } ?>
</ul>

I liked a lot the approach not having to deal with the opening/closing HTML tags and writing the attributes includeing the = 's and " 's.

Like:

<?= HTML::anchor($url, $title, array('class' => $class)) ?>

renders as:

<a href="http://url.my/" class="my-class">My Title</a>

How do you handle this kind of templateing? Do you know some goot templatetag-libraries that address this situation? Is it at all possible in django-templates or does their logic follow different paths/concepts?


回答1:


You could do that by defining something i'd like to call "partials", which are technically normal templates. Let me show you an example.

Your main template:

<ul>
{% for item in items %}
<li>
    {% include "partial/link.html" with url=item.get_absolute_url, title=item.title, active=item.active, image=item.image %}
</li>
{% endfor %}
</ul>

partial/link.html:

<a class="{% if active %}active{% endif %}" title="{{ title }}" href="{{ url }}">
    <img src="{% thumbnail image 24x24 crop upscale %}" />{{ title|truncate_chars:30 }}
</a>


来源:https://stackoverflow.com/questions/11627342/elegant-and-efficient-way-for-django-templates

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