【问题标题】:Include template by variable按变量包含模板
【发布时间】:2020-08-07 08:31:56
【问题描述】:

我有一个这样的模型:

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]

【问题讨论】:

  • 如果您尝试使用绝对路径而不是相对路径会怎样?
  • ^ 已解决。谢谢你。不知道为什么它不能将相对值作为变量使用,但绝对路径也可以正常工作。

标签: django


【解决方案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 中查找:答案是使用绝对路径而不是相对路径。

【讨论】:

  • 谢谢,很高兴知道它应该可以工作。找不到其他尝试过此方法的人(可能是因为它通常有效)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 2015-06-21
  • 2012-01-19
  • 1970-01-01
相关资源
最近更新 更多