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

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

问题描述

Django 创建可重用模板的方式是什么?

What is the Django way of creating a reusable template?

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

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?

通读 Django 的模板文档 我的印象是 Django 模板提供自上而下"子模板本身决定将嵌入哪个超级模板的继承:

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?

推荐答案

重用模板片段最灵活的方式是 定义一个包含标签.您可以将参数传递给您的自定义标记,在 Python 中对其进行一些处理,然后返回到模板.直接包含仅适用于不依赖于周围上下文的片段.

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.

文档中的快速示例:

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

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}

app/templates/results.html 中:

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

调用标签:

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

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

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