按变量包含模板

时间:2020-08-07 08:31:56

标签: django

我有一个这样的模型:

class Component(models.Model)
    html_name = models.CharField(max_length=100) #example value: header_1.html

class MyModel(models.Model):
    components = models.ManyToManyField(Component ...)

在我的Django项目中,我具有以下结构。

root
----myapp
--------templates
------------myapp
----------------templates
--------------------default_template_1.html
----------------components
--------------------header_1.html

在我的模板(default_template_1.html)中,我想做这样的事情:

{% for applied_component in mymodel.components.all %}
    {% with '../components/'|add:applied_component as component_template %}
        {% include component_template %}
    {% endwith %}
{% endfor %}

这给了我一个错误:TemplateDoesNotExist。但是,如果我在component_template中提取该字符串并对其进行硬编码,则include可以正常工作。因此,似乎它是一个变量。

我还尝试将包含更改为:{% include component_template|stringformat:"i" %} 但这给了我

PermissionError at /app/event/1/
[Errno 13]

1 个答案:

答案 0 :(得分:1)

我使用模板变量作为包含字符串,对于我的系统来说,它可以正常工作:

{% with settings.get_template as template %}
{% if template %}
<div class="setupFormWrapper">
  <form action="{% url 'simple:setup:products:settings_set' selected.id %}" method="POST" id="settingsForm" class="form{{ settings.formClass }}">
    {% csrf_token %}
    {{ template }}
  </form>
</div>

因此,您要做的事情绝对有可能。您确定要正确构建路径,并且模板引擎具有处理模板的访问权限吗?

在Google中可查找性:答案是使用绝对路径而不是相对路径。