One of the things that keeps coming up from my users is a need to
count the number of items that matched an if condition. My first
reaction was to add some counters to drops, but I don't know what all
they're going to want to count.
Is there currently any facility for something like {% assign a = a + 1
%} (which I already know doesn't work)?
If not, what about the following syntax:
{% newcounter a %}
{% increment a %}
{% decrement a %}
I'll be happy to write it, but don't want to re-invent the wheel.
Suggestions on a better approach encouraged.
I just went ahead and wrote the things. I called it counter, not
newcounter.
class Counter < Liquid::Tag
Syntax = /(#{Liquid::VariableSignature}+)/
def initialize(tag_name, markup, tokens)
if markup =~ Syntax
@to = $1
else
raise SyntaxError.new("Syntax Error in 'newcounter' - Valid
syntax: newcounter [var]")
end
super
end
def render(context)
context.scopes.last[@to.to_s] = 0
''
end
end
Liquid::Template.register_tag('counter', Counter)
class Increment < Liquid::Tag
Syntax = /(#{Liquid::VariableSignature}+)/
def initialize(tag_name, markup, tokens)
if markup =~ Syntax
@to = $1
else
raise SyntaxError.new("Syntax Error in 'increment' - Valid
syntax: increment [var]")
end
super
end
def render(context)
context.scopes.last[@to.to_s] += 1
''
end
end
Liquid::Template.register_tag('increment', Increment)
class Decrement < Liquid::Tag
Syntax = /(#{Liquid::VariableSignature}+)/
def initialize(tag_name, markup, tokens)
if markup =~ Syntax
@to = $1
else
raise SyntaxError.new("Syntax Error in 'decrement' - Valid
syntax: decrement [var]")
end
super
end
def render(context)
context.scopes.last[@to.to_s] -= 1
''
end
end
Liquid::Template.register_tag('decrement', Decrement)
I'll make it a patch if you want one, but they're simple enough.
It looks like they may use a filter for that:
http://www.djangoproject.com/documentation/templates/#add