问题
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