Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Toolkit: how return a hash from a MACRO BLOCK

Is it possible to write macros or blocks that return a hash to the caller?

I tried to modularize some template code:

[%- 
MACRO MakeSomeThing(something) BLOCK;
  s = {  a => 'a',
         b => something,
         c => 'c'
      };
  # RETURN s;  # not allowed
  # s;         # just returns the hash ref string (HASH(0x32e42e4))
END;


  newOb =  MakeSomeThing('foo');
  dumper.dump({'newOb' => newOb});
%]

Is there some way to implement a similar pattern?

like image 712
vlad_tepesch Avatar asked Feb 19 '19 09:02

vlad_tepesch


1 Answers

I could not find a way when I was faced with the same problem.

As a workaround, you can pass in a reference and have the macro modify the referenced variable. This works for both arrays and hashes.

Example definition:

[%
   # usage: newOb={}; MakeSomeThing(newOb, something)
   MACRO MakeSomeThing(rv, something) BLOCK;
      rv.a = 'a';
      rv.b = something;
      rv.c = 'c';
   END;
%]

Example use:

[%
   newOb = {};
   MakeSomeThing(newOb, 'foo');
   dumper.dump({'newOb' => newOb});
%]
like image 101
ikegami Avatar answered Nov 15 '22 03:11

ikegami