2024-04-19 04:02:17 发布
网友
在django中,我有一个填充模板html文件的视图,但在html模板中,我希望包含另一个使用不同html模板的视图,如下所示:
{% block content %} Hey {{stuff}} {{stuff2}}! {{ view.that_other_function }} {% endblock content %}
这可能吗?
是的,您需要使用模板标记来执行此操作。如果只需要呈现另一个模板,则可以使用包含标记,或者可能只使用内置的{%include'path/to/template.html'%}
模板标记可以在Python中做任何事情。
http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/
[后续] 可以使用render_to_string方法:
from django.template.loader import render_to_string content = render_to_string(template_name, dictionary, context_instance)
您需要从上下文解析请求对象,或者在需要利用上下文实例时将其作为参数交给模板标记。
后续回答:包含标记示例
Django希望模板标记位于名为“templatetags”的文件夹中,该文件夹位于已安装应用程序中的应用程序模块中。。。
/my_project/ /my_app/ __init__.py /templatetags/ __init__.py my_tags.py #my_tags.py from django import template register = template.Library() @register.inclusion_tag('other_template.html') def say_hello(takes_context=True): return {'name' : 'John'} #other_template.html {% if request.user.is_anonymous %} {# Our inclusion tag accepts a context, which gives us access to the request #} <p>Hello, Guest.</p> {% else %} <p>Hello, {{ name }}.</p> {% endif %} #main_template.html {% load my_tags %} <p>Blah, blah, blah {% say_hello %}</p>
inclusion标记会呈现另一个模板(如您所需),但不必调用view函数。希望这能让你走。包含标签上的文档位于:http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#inclusion-tags
有人创建了一个模板标记loads a view。我试过了,而且有效。使用该模板标记的优点是不必重写现有视图。
用你的例子和你对布兰登回答的回答,这应该对你有用:
模板.html
{% block content %} Hey {{stuff}} {{stuff2}}! {{ other_content }} {% endblock content %}
视图.py
from django.http import HttpResponse from django.template import Context, loader from django.template.loader import render_to_string def somepage(request): other_content = render_to_string("templates/template1.html", {"name":"John Doe"}) t = loader.get_template('templates/template.html') c = Context({ 'stuff': 'you', 'stuff2': 'the rocksteady crew', 'other_content': other_content, }) return HttpResponse(t.render(c))
是的,您需要使用模板标记来执行此操作。如果只需要呈现另一个模板,则可以使用包含标记,或者可能只使用内置的{%include'path/to/template.html'%}
模板标记可以在Python中做任何事情。
http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/
[后续] 可以使用render_to_string方法:
您需要从上下文解析请求对象,或者在需要利用上下文实例时将其作为参数交给模板标记。
后续回答:包含标记示例
Django希望模板标记位于名为“templatetags”的文件夹中,该文件夹位于已安装应用程序中的应用程序模块中。。。
inclusion标记会呈现另一个模板(如您所需),但不必调用view函数。希望这能让你走。包含标签上的文档位于:http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#inclusion-tags
有人创建了一个模板标记loads a view。我试过了,而且有效。使用该模板标记的优点是不必重写现有视图。
用你的例子和你对布兰登回答的回答,这应该对你有用:
模板.html
视图.py
相关问题 更多 >
编程相关推荐