在管理面板中,我可以选择将用于显示内容的模板。我得出的结论是可以使用for循环,而不是使用if / elif语句进行多行处理。但是问题是我不知道如何将变量放入字符串中。可能吗
我尝试过这种方式:
{% include 'templates/template_'+ key + '.html' %}
{% include 'templates/template_{key}.html' %}
{% include f'templates/template_{key}.html' %}
但没有成功。
models.py
class Homepage(models.Model):
choice_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
TEMPLATE_TYPE = [
(choice_dict['one'], 'template-one'),
(choice_dict['two'], 'template-two'),
(choice_dict['three'], 'template-three'),
(choice_dict['four'], 'template-four'),
(choice_dict['five'], 'template-five'),
]
template = models.IntegerField('Optional', choices=TEMPLATE_TYPE, null=True, blank=True)
views.py
def index(request, *args, **kwargs):
homepage = Homepage.objects.first()
context = {
'homepage': homepage,
}
return render(request, 'home.html', context)
home.html
{% if homepage.template %}
{% for key, value in homepage.choice_dict.items %}
{% if homepage.template == value %} {% include 'templates/template_'+ key + '.html' %}{% endif %}
{% endfor %}
{% else %}
答案 0 :(得分:0)
views.py
template_name = 'templates/template_'+ key + '.html'
context = {
'homepage': homepage,
'template_name ': template_name ,
}
在模板中
{% if homepage.template %}
{% for key, value in homepage.choice_dict.items %}
{% if homepage.template == value %} {% include template_name %}{% endif %}
{% endfor %}
{% else %}
答案 1 :(得分:0)
您应该可以使用添加过滤器执行此操作
{% for key, value in homepage.choice_dict.items %}
{% if homepage.template == value %} {% include 'templates/template_'|add:key|add:'.html' %}{% endif %}
{% endfor %}