变量未在模板标签中显示值

时间:2018-10-18 05:09:38

标签: django django-templates

我在视图中有以下代码段:

image = [
    'register.png',
    'checkin.png',
    'checkin.png'
]
imagetext = [
    'Register Patient',
    'Checkin Patient',
    'Checkin Patient'
]
link = [
    '/clinic/%s/register' % cliniclabel,
    '/clinic/%s/checkin' % cliniclabel,
    '/clinic/%s/checkin' % cliniclabel
]
zipsidebarstuff = zip(image, imagetext, link)
return render(request, 'clinic/cliniccurrent3.html', 
              {'rnd_num': randomnumber(), 'clinic': clinicobj,
               'checked_list': checkedin_list, 'patientcount': patientcount,
               'type':'live', 'ClinicUserName': name, 'showhelp': helpneeded,
               'NumUnconfirmedAppts': NumUnconfirmedAppts(clinicobj),
               'zipsidebarstuff': zipsidebarstuff})

在我的模板中,我有:

<div class="col-md-6">
    <div class="sidebar-nav-fixed pull-right affix">
      <div class="row">
        <div class="d-inline-flex flex-row flex-wrap">
          {% for image, imagetext, link in zipsidebarstuff %}
          <div class="p-2 bd-white">
            <div class="d-inline-flex flex-column">
              <div class="p-2 flex-fill bd-highlight">
                <a href="{{ link }}"><img class="imgsidebtn" 
                   src="{% static 'clinic/img/{{ image }}' %}" /></a>
              </div>
              <div class="p-2 flex-fill bd-highlight">
                <a href="{{ link }}" class="btn btn-primary">{{ imagetext }}</a>
              </div>
            </div>
          </div>
          {% endfor %}
        </div>
      </div>
      {% include "clinic/helpbar.html" with location="livelist" foo=bar %}
  </div>
</div>

问题出在显示标签

<a href="{{ link }}"><img class="imgsidebtn" 
                          src="{% static 'clinic/img/{{ image }}' %}" /></a>
呈现的html中的

。显示为:

<a href="/clinic/jeslineye/checkin"><img class="imgsidebtn"
 src="/appointments/static/clinic/img/%7B%7B%20image%20%7D%7D"></a>

为什么会这样?我该如何解决?

2 个答案:

答案 0 :(得分:2)

您不能在static标签内使用模板变量,如下所示:

{% static 'clinic/img/{{ image }}' %}

请改为使用withadd过滤器

{% with "clinic/img/"|add:image as image_url %}{% static image_url %}{% endwith %}

答案 1 :(得分:1)

您不能在{% static %}标记内使用变量。您可以使用get-static-prefix并手动构造URL。例如:

<img src="{% get_static_prefix %}clinic/img/{{ image }}">