Html 将变量分配给 {% include %} 标记 Django 中的子模板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11639306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assign variables to child template in {% include %} tag Django
提问by Vor
I have this code(which doesn't give me expected result)
我有这个代码(它没有给我预期的结果)
#subject_content.html
{% block main-menu %}
{% include "subject_base.html" %}
{% endblock %}
#subject_base.html
....
....
<div id="homework" class="tab-section">
<h2>Homework</h2>
{% include "subject_file_upload.html" %}
</div>
child template:
子模板:
#subject_file_upload.html
<form action="." method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit">
</form>
and my view
和我的看法
#views.py
@login_required
def subject(request,username, subject):
if request.method == "POST":
form = CarsForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect("/")
form = CarsForm()
return render_to_response('subject_content.html', {'form':form}, context_instance=RequestContext(request))
The above code creates HTML in the way I want it to be, however the form does not update database.
上面的代码以我想要的方式创建 HTML,但是表单不会更新数据库。
BUT,
但,
If I skip the middle template and go directly to the uploading form, it works fine:
如果我跳过中间模板并直接进入上传表单,它工作正常:
#subject_content.html
{% block main-menu %}
{% include "subject_file_upload.html" %}
{% endblock %}
Help me please to make it work with middle template. I want to do this, because I don't wan't to type the same code more than once.
请帮助我使其与中间模板一起使用。我想这样做,因为我不想多次输入相同的代码。
回答by Vor
Like @Besnik suggested, it's pretty simple:
就像@Besnik 建议的那样,这很简单:
{% include "subject_file_upload.html" with form=form foo=bar %}
The documentation for include
mentions this. It also mentions that you can use only
to render the template with the given variables only, without inheriting any other variables.
在对文件include
提到了这一点。它还提到您可以仅使用only
给定的变量来呈现模板,而无需继承任何其他变量。
Thank you @Besnik
谢谢@Besnik