Django自定义标签需要3个参数,但只提供了2个。

huangapple go评论90阅读模式
英文:

Django custom tags requires 3 arguments, 2 provided

问题

  1. #custom_tags.py
  2. def modulo(value, number, number2):
  3. mod = value % number
  4. if mod == number2:
  5. return True
  6. else:
  7. return False
  1. {% comment %} index.html {% endcomment %}
  2. {% for post in posts|slice:"1:" %}
  3. {% if post.id|modulo:4:0 %}
  4. <div class="post-entry-1">
  5. <a href="{{post.slug}}"><img src="{{post.image.url}}" alt="" class="img-fluid"></a>
  6. <div class="post-meta"><span class="date">{{post.category}}</span> <span class="mx-1">•</span> <span>{{post.created_date}}</span></div>
  7. <h2><a href="single-post.html">{{ post.title }}</a></h2>
  8. </div>
  9. {% endif %}
  10. {% endfor %}

TemplateSyntaxError at /blog/ modulo requires 3 arguments, 2 provided

当我使用变量 number 对值进行取模运算时,我想用变量 number2 检查结果。

英文:
  1. #custom_tags.py
  2. def modulo(value, number,number2):
  3. mod = value % number
  4. if mod == number2:
  5. return True
  6. else:
  7. return False
  1. {% comment %} index.html {% endcomment %}
  2. {% for post in posts|slice:"1:"%}
  3. {% if post.id|modulo:4:0 %}
  4. <div class="post-entry-1">
  5. <a href="{{post.slug}}"><img src="{{post.image.url}}" alt="" class="img-fluid"></a>
  6. <div class="post-meta"><span class="date">{{post.category}}</span> <span class="mx-1">•</span> <span>{{post.created_date}}</span></div>
  7. <h2><a href="single-post.html">{{ post.title }}</a></h2>
  8. </div>
  9. {% endif %}
  10. {% endfor %}

> TemplateSyntaxError at /blog/ modulo requires 3 arguments, 2 provided

When I mod the value with the variable number, I want to check the result with the variable number2

答案1

得分: 3

你定义了一个过滤器,而不是一个标签。标签最多可以带两个参数,一个是标签应用的对象,另一个是可选参数。

你可以这样定义一个标签:

  1. from django import template
  2. register = template.Library()
  3. @register.simple_tag
  4. def modulo(value, number, number2=0):
  5. return value % number == number2

然后你可以这样使用它:

  1. {% modulo post.id 4 as md %}
  2. {% if md %}
  3. …
  4. {% endif %}

尽管如此,你的模板似乎实现了业务逻辑。这不应该放在模板中,而应该放在视图中。

英文:

You defined a filter, not a tag. A tag can (at most) take two parameters. The object on which the tag is applied and an optional parameter.

You can define a tag with:

<pre><code>from django import template

register = template.Library()

@register<b>.simple_tag</b>
def modulo(value, number, number2=0):
return value % number == number2</code></pre>

Then you use this with:

<pre><code>{% <b>modulo post.id 4 as md</b> %}
{% if md %}
&hellip;
{% endif %}</code></pre>

That being said, your template seems to implement business logic. This does not belong in the template, but in the view.

huangapple
  • 本文由 发表于 2023年3月15日 19:20:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744010.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定