Custom Tag, Drop or Filter

39 views
Skip to first unread message

David

unread,
Jun 30, 2009, 10:46:27 AM6/30/09
to Liquid Templates
Hi all,

I have recently started using Liquid and while I am fairly comfortable
with the basics I am now unsure as to what method I should be using to
achieve what I want in the template.

In my example I have 3 models: Questionnaire, Question and Tag. A
Questionnaire has many Questions and a Question has and belongs to
many Tags. I have a method in my Questionnaire model which will allow
me to count the number of questions in the questionnaire that have
been tagged with a tag whose name matches the given parameter. E.g.

def count_questions_with_tag(tag_name)
tag = Tag.find_by_name(tag_name)
questions_with_tag = self.questions.find_all {|q| q.tags.include?
(tag)}
return questions_with_tag.length
end

Basically, I am rendering the template and passing a questionnaire as
a variable. I then want to be able to call
questionnaire.count_questions_with_tag("tag1") and somehow display
that in the template.

I have tried it with a filter without much luck, I also tried a custom
tag which worked but I couldn't work out how to pass more than one
custom parameter to it (the questionnaire and the tag name). I also
read a bit about Drops but am not really sure how they fit in.

Does anyone have a suggestion as to what method I should be using to
accomplish what I set out above?

Any help is much appreciated!

Cheers

Brian Candler

unread,
Jun 30, 2009, 2:35:13 PM6/30/09
to liquid-t...@googlegroups.com
On Tue, Jun 30, 2009 at 07:46:27AM -0700, David wrote:
> Basically, I am rendering the template and passing a questionnaire as
> a variable. I then want to be able to call
> questionnaire.count_questions_with_tag("tag1") and somehow display
> that in the template.
>
> I have tried it with a filter without much luck

A filter is the easiest way to pass arguments. That is:

{{ questionnaire | count_questions_with_tag: "tag1" }}

> I also
> read a bit about Drops but am not really sure how they fit in.

I added some notes on this at the bottom of
http://wiki.github.com/tobi/liquid/using-liquid-without-rails

A 'Drop' is the mechanism by which the method-call type operations are
performed, e.g. foo.bar, which ends up calling invoke('bar') on the foo
drop. Unfortunately, as far as I can see, there's no mechanism to pass
arguments this way.

Reply all
Reply to author
Forward
0 new messages