Django从文件导入模板 [英] django import template from file

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

问题描述

我有3页,并且每个页面的HTML文件顶部都有相同的菜单.

I have 3 pages, and all of them have the same menu on the top of each html file.

菜单中有很多标签,当我想修改标签中的所有链接时遇到问题.

There are many a tags in the menu, and I have problem when I'd like to revised all link in a tag.

我想将菜单写到另一个名为menu.txt的文件中,并使用模板加载menu.txt,然后将菜单与页面的其他部分合并.

I'd like to write the menu in other file called menu.txt, and use template to load the menu.txt and then combine menu with other parts of the page.

有效率的方法吗?

除了将页面加载到view.py中并将值传递给模板之外.

Except load the page in view.py and pass value to template.

谢谢.

推荐答案

模板继承

Django模板引擎中最强大(因此也是最复杂)的部分是模板继承.通过模板继承,您可以构建基本的骨架"模板,该模板包含网站的所有常见元素并定义子模板可以覆盖的块.

The most powerful – and thus the most complex – part of Django’s template engine is template inheritance. Template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines blocks that child templates can override.

从一个示例开始,最容易理解模板继承:

It’s easiest to understand template inheritance by starting with an example:

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="sidebar">
        {% block sidebar %}
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/blog/">Blog</a></li>
        </ul>
        {% endblock %}
    </div>

    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>

此模板(我们称为base.html)定义了一个简单的HTML框架文档,您可以将其用于一个简单的两列页面.子"模板的工作是用内容填充空白块.

This template, which we’ll call base.html, defines a simple HTML skeleton document that you might use for a simple two-column page. It’s the job of "child" templates to fill the empty blocks with content.

在此示例中,block标签定义了三个子模板可以填充的块.所有block标签所做的就是告诉模板引擎子模板可以覆盖模板的那些部分.

In this example, the block tag defines three blocks that child templates can fill in. All the block tag does is to tell the template engine that a child template may override those portions of the template.

子模板可能看起来像这样:

A child template might look like this:

{% extends "base.html" %}
{% block title %}My amazing blog{% endblock %}
{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}

extends标签是这里的关键.它告诉模板引擎该模板扩展"了另一个模板.模板系统评估该模板时,首先会找到父模板-在这种情况下为"base.html".

The extends tag is the key here. It tells the template engine that this template "extends" another template. When the template system evaluates this template, first it locates the parent – in this case, "base.html".

您可以参考扩展每个html页面上的commom部分

you can refer for extending commom part on each html page

http://www.webforefront.com/django/createreusabledjangotemplates.html

这篇关于Django从文件导入模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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