From d6c923163c0a5b6156764750fa03b963e3bef800 Mon Sep 17 00:00:00 2001 From: Oskar Pearson Date: Tue, 5 Apr 2016 14:25:05 +0100 Subject: [PATCH] Added information about how to use assignments in a custom Liquid::Tag --- Liquid-for-Programmers.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/Liquid-for-Programmers.md b/Liquid-for-Programmers.md index 1911b20..06e2ad8 100644 --- a/Liquid-for-Programmers.md +++ b/Liquid-for-Programmers.md @@ -112,6 +112,35 @@ Liquid::Template.register_tag('random', Random) @template.render # => "3" ``` +### Using Assignments in Templates + +```ruby +class Multiply < Liquid::Tag + def initialize(tag_name, factor, tokens) + super + @factor = factor.to_f + end + + def render(context) + (@factor * context["multiply_by"].to_f).to_s + end +end + +Liquid::Template.register_tag('multiply', Multiply) +``` + +```ruby +@template = Liquid::Template.parse("{% multiply 5 %}") +@template.assigns["multiply_by"] = 10 +@template.render # => "50" +``` +or +```ruby +@template = Liquid::Template.parse("{% multiply 5 %}") +@template.render('multiply_by' => 3) # => 15 +``` + + ### Create your own tag blocks "Blocks" are tags that contain a block of template code which is delimited by a `{% end %}` tag. The opening tag of a block can also take any number of arguments.