Можно ли вставить строку с переменной внутри тега include? - PullRequest
0 голосов
/ 16 октября 2019

В админ-панели я могу выбрать, какой шаблон будет использоваться для отображения контента. Вместо нескольких строк с оператором if / elif я пришел к выводу, что могу использовать цикл for. Однако проблема в том, что я не знаю, как поместить переменную в строку. Это вообще возможно?

Я пробовал это так:

{% 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 %}

Ответы [ 2 ]

0 голосов
/ 16 октября 2019

Вы должны быть в состоянии использовать фильтр добавления, чтобы сделать это

    {% for key, value in homepage.choice_dict.items %}
        {% if homepage.template == value %} {% include 'templates/template_'|add:key|add:'.html' %}{% endif %}
    {% endfor %}
0 голосов
/ 16 октября 2019

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 %}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...