【问题标题】:Django templates - Formatting stringsDjango 模板 - 格式化字符串
【发布时间】:2014-09-02 11:31:56
【问题描述】:

我有这些变量:

#Int
user.id

#Float (e.g. X.YYYY)
profile.rating

我需要这些格式(` 是分隔符):

<a href="/user/`user.id`/">`profile.rating`</a>

我尝试了很多方法来格式化它们,但都没有奏效。例如,连接它们:"&lt;a href=\"/user/"|add:user.id|add:"\"&gt;"|add:profile.rating|add:"&lt;/a&gt;" 什么都没有给我(字面意思是,nothing)。

我怀疑这是因为add: 是数字优先的,但是使用slugifystringformat:"" 将数字转换为字符串再次给了我,什么都没有

我该怎么做?

请注意:我需要使用过滤器来执行此操作,因为结果将作为参数传递给包含。

更新: 基本上,我正在构建一种模块化包含。它包括如下所示:

<section>
...

  {% if custom_section %}
  <section id="{{ custom_section_id }}">
    {{ custom_section }}
  </section>
  {% endif %}

...
</section>

这意味着我不能直接在参数中包含值,我需要将在嵌套 section 中的标记。

【问题讨论】:

  • 你想要什么样的输出?为什么像 "/user/{{user.id}}/" 这样的东西不适合你?
  • 但是当将值作为参数“包含”到包含中时,这不是不可能吗? IE。 {% include "XX" with stuff="/user/{{ user.id }}/" %}?
  • 你能详细说明这个作为参数传递给包含 - 你的意思是{% include %} 标签吗?
  • include-标签,是的。如{% include with param="" %},其中param 是一个参数。
  • 致那些投反对票的人:如果你至少能告诉我为什么你投反对票,那就太好了。

标签: django django-templates


【解决方案1】:

我设法用这段标记解决了这个问题:

{% with "<a href="\"/user/" as link_start %}
  {% with profile.rating|stringformat:".1f" as rating %}
    {% with user.id|slugify as id %}
      {% with link_start|add:id|add:"/\">" as link %}
        {% with link|add:rating|add:"/5</a>" as data %}
          {% include "XX" with custom_data:data|safe %}

 {% endwith %} a couple of times

这里的关键是|stringformat:".1f"user.id|slugify,因为没有它们,djangos worthless 模板语言默认所有值都是数字的,因此废话就出来了。

值得注意的是|safe,因为没有它,语言会转义值。

【讨论】:

    【解决方案2】:

    请注意:我需要使用过滤器执行此操作,因为结果将是 作为参数传递给包含。

    您可以直接将它们传递给包含,因为它会正确获取上下文。

    {% include user.id %}
    

    【讨论】:

      猜你喜欢
      • 2011-08-03
      • 2012-07-22
      • 2010-09-25
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多