英文:
Django custom tags requires 3 arguments, 2 provided
问题
#custom_tags.py
def modulo(value, number, number2):
mod = value % number
if mod == number2:
return True
else:
return False
{% comment %} index.html {% endcomment %}
{% for post in posts|slice:"1:" %}
{% if post.id|modulo:4:0 %}
<div class="post-entry-1">
<a href="{{post.slug}}"><img src="{{post.image.url}}" alt="" class="img-fluid"></a>
<div class="post-meta"><span class="date">{{post.category}}</span> <span class="mx-1">&bullet;</span> <span>{{post.created_date}}</span></div>
<h2><a href="single-post.html">{{ post.title }}</a></h2>
</div>
{% endif %}
{% endfor %}
TemplateSyntaxError at /blog/ modulo requires 3 arguments, 2 provided
当我使用变量 number 对值进行取模运算时,我想用变量 number2 检查结果。
英文:
#custom_tags.py
def modulo(value, number,number2):
mod = value % number
if mod == number2:
return True
else:
return False
{% comment %} index.html {% endcomment %}
{% for post in posts|slice:"1:"%}
{% if post.id|modulo:4:0 %}
<div class="post-entry-1">
<a href="{{post.slug}}"><img src="{{post.image.url}}" alt="" class="img-fluid"></a>
<div class="post-meta"><span class="date">{{post.category}}</span> <span class="mx-1">&bullet;</span> <span>{{post.created_date}}</span></div>
<h2><a href="single-post.html">{{ post.title }}</a></h2>
</div>
{% endif %}
{% 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
你定义了一个过滤器,而不是一个标签。标签最多可以带两个参数,一个是标签应用的对象,另一个是可选参数。
你可以这样定义一个标签:
from django import template
register = template.Library()
@register.simple_tag
def modulo(value, number, number2=0):
return value % number == number2
然后你可以这样使用它:
{% modulo post.id 4 as md %}
{% if md %}
…
{% 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 %}
…
{% endif %}</code></pre>
That being said, your template seems to implement business logic. This does not belong in the template, but in the view.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论