【问题标题】:How to use dictionary variables inside django static tag如何在 django 静态标签中使用字典变量
【发布时间】:2019-04-12 07:24:35
【问题描述】:

我正在尝试将 Django 变量连接到 img src。我找到了一个solution 来执行此操作,但是当我检查浏览器时,该值仍然没有显示出来。顺便说一句,我调用的值是 dict 类型,看起来像这样 >>> djangoDict 输出:{<foreignModel: ModelValue>: <Product: Item Desc...}

我能够使用 2 个花括号 {{ djangoDict }} 显示 ModelValue,但在与地址连接时我不能这样做。

所以这里是我的代码:

{% for dd in djangoDict %}
            {% with 'products/anotherFolder/'|add:dd|add:'/suffix.jpg' as myImg %}
              <a class="dropdown-item" data-img="{% static myImg %}">{{ dd }}</a>
            {% endwith %}
{% endfor %

这是我在检查元素时得到的:

<a class="dropdown-item" data-img="/assets/suffix.jpg">ModelValue</a>

我想展示的内容:

<a class="dropdown-item" data-img="/assets/products/anotherFolder/ModelValue/suffix.jpg">ModelValue</a>

非常感谢任何可以提供帮助的人:)

【问题讨论】:

  • 使用{% for k, v in dict.items() %} 循环浏览字典
  • @RockyLi 它没有出现。 img src 还是一样的。输出为&lt;a class="dropdown-item" data-img="/assets/products/suffix.jpg"&gt;Item desc...&lt;/a&gt;

标签: python django-templates django-views django-staticfiles


【解决方案1】:

我看到了一个与我类似的问题,它解决了我在连接图像路径方面的问题。 It is the best answer 我的问题。

我使用了在 settings.py 中配置的STATIC_URL

我的代码现在看起来像这样:

{% for dd in djangoDict %}
    <a class="dropdown-item" data-img="{{ STATIC_URL }}products/anotherFolder/{{ dd }}/suffix.jpg">{{ dd }}</a>
{% endfor %}

【讨论】:

    【解决方案2】:

    我也发现自己面临着类似的问题,我不知道它是否完全相同;我想将静态文件夹中的文件链接到我的 HTML 文件,即src="",该目录应该来自字典源。 显然,您可以直接将其链接到那里。这是我的代码的一部分;

    {% for dic in posts %}
    {% if dic.no == 1 %}
    <img alt="" class="u-expanded-width u-image u-image-default src="{% static dic.src %}"><!--/product_image--><!--product_title-->
    <h4 class="u-product-control u-text u-text-body-alt-color u-text-2">
    <a class="u-product-title-link" href="#"><!--product_title_content-->{{ dic.name }}<!--/product_title_content--></a>
    {% endif %}
    {% endfor %}

    【讨论】:

    • 我无法理解 Jeanawhou 的回答
    • 您可以像我一样处理视图上的路径并将其添加到字典中以在您的 html 代码中使用?‍♂️。
    猜你喜欢
    • 2013-05-15
    • 1970-01-01
    • 2015-04-18
    • 2014-01-03
    • 2015-11-25
    • 1970-01-01
    • 2012-02-04
    • 2017-11-30
    • 2014-08-09
    相关资源
    最近更新 更多