[stringtemplate-interest] Templates that get another templates as arguments?

Barrie Treloar baerrach at gmail.com
Sun Jun 26 16:55:20 PDT 2011


2011/6/27 Дмитрий Васильев <dmitry.vasil at gmail.com>:
> Consider the following example. I have a template that greets my friends:
>
> greet()::=<<
> <hello("Bob")>
> <hello("John")>
> <hello("Kate")>
> <hello("Barbara")>
>>>
>
> hello(name)::=<<
> Hello, <name>!
>>>
>
> Sometimes I want print their names in bold:
>
> hello(name)::=<<
> Hello, [b]<name>[/b]!
>>>
>
> Sometimes I want to prepend their names with the word "dear":
>
> hello(name)::=<<
> Hello, dear <name>!
>>>
>
> Generally, I want to pass a template for handling various cases as an
> argument to template 'greet()'. I want to be able to do something like this:
>
> greet(processName)::=<<
> <hello("Bob")>
> <hello("John")>
> <hello("Kate")>
> <hello("Barbara")>
>>>
>
> hello(name)::=<<
> Hello, <processName(name)>
>>>
>
> bold(text)::=<<
> [b]<text>[/b]
>>>
>
> dear(name)::=<<
> dear <name>
>>>
>
> greet_in_bold()::=<<
> <greet(processName=bold)>
>>>
>
> greet_dear()::=<<
> <greet(processName=dear)>
>>>
>
> But I can't find how I can do something similar with StringTemplate. Do I
> miss something obvious?

I'm sorry that I dont have time to hack your scripts to show this
working, I can only throw some comments over the wall and let you
attempt them.
Hopefully you will get a better answer but this may get you moving in
the mean time.

Your hello template can take another argument which is the template
that will be applied.

hello(name, processName)::=<<
Hello, <processName(name)>
>>

Then greet becomes
greet(processName)::=<<
<hello("Bob",processName)>
<hello("John",processName)>
<hello("Kate",processName)>
<hello("Barbara",processName)>
>>

Alternatively, apply the template outside of the hello template:

Leave
hello(name)::=<<
Hello, <name>!
>>

And greet becomes
greet(processName)::=<<
<hello(<processName("Bob")>)>
<hello(<processName("John")>)>
<hello(<processName("Kate")>)>
<hello(<processName("Barbara")>)>
>>

You may also be better off using a list to apply templates over, see
http://www.antlr.org/wiki/display/ST4/StringTemplate+cheat+sheet

(You may need to wrap this in a list []...)
< "Bob", "John", "Kate", "Barbara" : { name |  greet(name, processName=bold)}>
or
< "Bob", "John", "Kate", "Barbara" : { name |  greet(<bold(name)>)}>
Depending on which way you decide to go.

Its too early in the morning to think about what the correct advice should be.
I think one way is better than the other, for all the usual comp. sci.
reasons of good design.


More information about the stringtemplate-interest mailing list