如何将代码块包含到除基本.htm

2024-04-23 15:33:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要用form创建一个小的侧块(它只包含一个字段和按钮),我希望它包含在除base.html之外的每个页面中

我想做一个简单的视图函数,但也许有更好的方法来做到这一点?你知道吗

我正在使用Python和django1.6


Tags: 方法函数form视图basehtml页面按钮
3条回答

可以在中使用块标记基本.html,我想你是在找这样的东西

你知道吗基本.html你知道吗

{% block code %}
 {% include 'sidebar.html' %}
{% endblock %}

你知道吗索引.html你知道吗

{% extends base.html %}
{% block code %}
{% endblock %}

以及其他模板 只需扩展基本html

{% extends base.html %}

你必须使用模板来做这件事。 换句话说,尝试创建$DJANGO\u根/模板/主.html使用以下代码:

<html>
<head>
</head>
<body>
 {% block one_field_and_a_button %}
   <input />
   <button>I am everywhere</button>
 {% endblock %}
 {% block my_custom_content %}
 {% endblock %}
</body>
<html>

然后所有其他模板都必须扩展它主.html模板并插入自己的数据。 假设这是$DJANGO\u ROOT/templates/登录.html.它将只替换“我的\u自定义\u内容”,并将继承所有其他块,包括“一个\u字段\u和一个\u按钮”

{% extends 'templates/main.html' %}
{% block my_custom_content %} 
 Hello World! This is the login
{% endblock %}

最后,如果你想基本.html如果没有包含一个字段和一个按钮的代码部分,可以执行以下操作。 假设这是$DJANGO\u ROOT/templates/基本.html。它将同时替换“一个字段和一个按钮”和“我的自定义内容”。但是,在这种情况下,“one\ field\和\ a\ button”将被替换为不会在html代码中显示的空格。你知道吗

{% extends 'templates/main.html' %}
{% block one_field_and_a_button %} {% endblock %}
{% block my_custom_content %} 
 Hello World! This is my base.html template
{% endblock %}

希望对你有用!你知道吗

一般来说,你不应该使用基本.html直接,但是因为你是,而且在其他模板中更改它会非常麻烦,所以你能做的是,在返回的视图函数中基本.html,可以将布尔值添加到上下文中,并检查布尔值以确定使用的模板。你知道吗

像这样:

def view_that_uses_base.html(request):
   is_base = True
   return render_to_response("base.html", {"is_base":is_base}, RequestContext(request,{}))

然后在模板中:

{% block sidebar %}
{% if is_base%}
{% else %}

#Your code here
{% endif %}
{% endblock sidebar %}

相关问题 更多 >