如何在Django中创建可重用的模板? [英] How to make a reusable template in Django?

查看:156
本文介绍了如何在Django中创建可重用的模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例:假设我的许多网页包含最新消息框并遵循DRY原则,我想定义一次,并在其他页面中重用它。如何使用Django(或 Jinja2 )模板进行此操作?



通过 Django的模板文档阅读我得到的印象是,Django模板提供自上而下的继承,子模板本身确定要嵌入的超级模板:

 <! - 超级模板(无效,图示): - > 
< html>
< head>< title>标题< / title>< / head>
< body> {%block content%} {%endblock%}< / body>
< / html>





 <! - 子模板: - > 
{%extendsbase.html%}
{%block content%}
< div class =latest-news>新闻< / div>
{%endblock%}

那么重用块的技术是什么

解决方案

重用模板片段的最灵活方式是< a href =https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags>定义一个inclusion_tag 。您可以将参数传递到您的自定义标签,在Python中处理它们,然后弹回到模板。 直接包含仅适用于不依赖于周围环境的片段。



文档的快速示例:



app / templatetags / poll_extras.py 注册带有装饰的标签:

 从django导入模板
register = template.Library ()

@ register.inclusion_tag('results.html')
def show_results(poll):
choice = poll.choice_set.all()
return { 'choice':choices}

app / templates / results.html

 < ul> 
{%在选择中选择%}
< li> {{choice}}< / li>
{%endfor%}
< / ul>

调用标签:

  {%load poll_extras%} 
{%show_results poll%}


What is the Django way of creating a reusable template?

Example: Suppose a lot of my pages contain a "Latest News" box and following the DRY principle, I would like to define it once and reuse it in the other pages. How would I do this with Django (or Jinja2) templates?

Reading through Django's Template Documentation I get the impression that Django templates offer "top-down" inheritance where the sub-template itself determines in which super-template it is going to be embedded:

<!-- Super-template (not valid, for illustration): -->
<html>
  <head><title>Title</title></head>
  <body>{% block content %}{% endblock %}</body>
</html>

<!-- Sub-template: -->
{% extends "base.html" %}
{% block content %}
<div class="latest-news">News</div>
{% endblock %}

So what is the technique to reuse a block (a sub-template) in several places?

解决方案

The most flexible way to reuse template fragments is to define an inclusion_tag. You can pass arguments to your custom tag, process them a bit in Python, then bounce back to a template. Direct inclusion only works for fragments that don't depend on the surrounding context.

Quick example from the docs:

In app/templatetags/poll_extras.py register the tag with a decoration:

from django import template
register = template.Library()

@register.inclusion_tag('results.html')
def show_results(poll):
    choices = poll.choice_set.all()
    return {'choices': choices}

In app/templates/results.html:

<ul>
{% for choice in choices %}
    <li> {{ choice }} </li>
{% endfor %}
</ul>

Calling the tag:

{% load poll_extras %}
{% show_results poll %}

这篇关于如何在Django中创建可重用的模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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