重用HTML布局对象的模板

时间:2020-12-21 12:02:45

I would like to add to my form layout an HTML layout object, reusing an existing template, but I have not been able to get it to work. This is what I am doing:

我想在我的表单布局中添加一个HTML布局对象,重用现有模板,但我无法让它工作。这就是我在做的事情:

HTML(loader.get_template('my-template.html'))

But get_template is giving me a Template, not a string, and it breaks.

但get_template给了我一个模板,而不是一个字符串,它打破了。

Can I do something else to get this working?

我可以做一些其他工作吗?

EDIT

More rationale:

更多理由:

I am looking for the raw template string, since I want to reuse a template for a layout component, which will be rendered later in the context of the page being accessed. When it is rendered, I want it to behave as it would be rendered in a normal template processing step.

我正在寻找原始模板字符串,因为我想重用一个布局组件的模板,稍后将在被访问页面的上下文中呈现。渲染时,我希望它的行为与在普通模板处理步骤中渲染的行为相同。

I would like to avoid pre-rendering because it seems unsafe to me, since I do not think that it is guaranteed that this gives me back exactly the same template string as I have in disk. And I would really like to avoid having another source of strange and hard to debug problems.

我想避免预渲染,因为它对我来说似乎不安全,因为我不认为这可以保证这会让我返回与我在磁盘中完全相同的模板字符串。而且我真的希望避免另一个奇怪且难以调试问题的来源。

EDIT2

This is my current, working hack (even on Heroku):

这是我目前的工作黑客(即使是在Heroku上):

# TODO: this is a hack
template_str = open(os.path.join(settings.BASE_DIR, 'templates', 'my-template.html')).read()

    ...
    HTML(template_str),
    ...

2 个解决方案

#1


1  

You can access the unmodified template string at Template.source:

您可以在Template.source访问未修改的模板字符串:

template = loader.get_template('my-template.html')
HTML(template.source)

However I think it will be more efficient (and less magical) just to do:

但是我觉得这样做会更有效(而且不那么神奇):

HTML('{% include "my-template.html" %}')

#2


0  

You can use render_to_string():

您可以使用render_to_string():

from django.template.loader import render_to_string

html = render_to_string('your-template.html', {})
HTML(html)

#1


1  

You can access the unmodified template string at Template.source:

您可以在Template.source访问未修改的模板字符串:

template = loader.get_template('my-template.html')
HTML(template.source)

However I think it will be more efficient (and less magical) just to do:

但是我觉得这样做会更有效(而且不那么神奇):

HTML('{% include "my-template.html" %}')

#2


0  

You can use render_to_string():

您可以使用render_to_string():

from django.template.loader import render_to_string

html = render_to_string('your-template.html', {})
HTML(html)