django - 是否可以在包含标签内插入带有变量的字符串?
问题描述
在管理面板中,我可以选择将使用哪个模板来显示内容。我得出的结论是我可以使用 for 循环,而不是多行 if/elif 语句。但是问题是我不知道如何将变量放在字符串中。甚至可能吗?
我试过这种方法:
{% include 'templates/template_'+ key + '.html' %}
{% include 'templates/template_{key}.html' %}
{% include f'templates/template_{key}.html' %}
但没有成功。
模型.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)
视图.py
def index(request, *args, **kwargs):
homepage = Homepage.objects.first()
context = {
'homepage': homepage,
}
return render(request, 'home.html', context)
主页.html
{% if homepage.template %}
{% for key, value in homepage.choice_dict.items %}
{% if homepage.template == value %} {% include 'templates/template_'+ key + '.html' %}{% endif %}
{% endfor %}
{% else %}
解决方案
视图.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 %}
推荐阅读
- python - 模型输出 "Tensor("activation_9/activation_9/Identity:0", shape=(?, 6), dtype=float32)" 的形状无效
- flutter - 为什么这里if语句中的条件不能满足
- flutter - FLUTTER / FIRESTORE - 检索嵌套在几个子集合中的数据
- upgrade - 从超过 3 个月大的 Drake 版本升级的最佳方式是什么?
- azure-log-analytics - Azure Sentinel,分析规则 14 天回溯限制
- angularjs - 在 Zeppelin Angular 段落中访问 angularBind 中的 JS 变量?
- javascript - 如何获取数组中的对角线值?
- java - 使用时间概念实现地图
- html - 如何通过剪辑路径过渡保持悬停效果?
- ios - 在 iOS 上提示生物识别权限时:我是否需要要求启用 TouchID?