首页 > 解决方案 > 是否可以在包含标签内插入带有变量的字符串?

问题描述

在管理面板中,我可以选择将使用哪个模板来显示内容。我得出的结论是我可以使用 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 %}

标签: djangodjango-templates

解决方案


视图.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 %}

推荐阅读