Django模板的优雅高效方法? [英] Elegant and efficient way for Django templates?

查看:64
本文介绍了Django模板的优雅高效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己最终得到了以下样式的模板片段:

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>

前段时间,ai必须使用一个PHP框架,该框架具有一些很好的HTML输出帮助器.我知道这不能直接比较,因为它不是 real 模板层(相当简单的PHP)-但有一个主意:

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>

我非常喜欢不必处理打开/关闭HTML标记并编写包含 = "的属性的方法.

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.

赞:

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

呈现为:

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

您如何处理这种模板化?您知道一些解决这种情况的goot templatetag库吗?在Django模板中是否完全有可能,或者它们的逻辑遵循不同的路径/概念?

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?

推荐答案

您可以通过定义我想称为"partials"的东西来做到这一点,这在技术上是正常的模板.让我给你看一个例子.

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

您的主模板:

<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:

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>

这篇关于Django模板的优雅高效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆