[stringtemplate-interest] [attr:tpl];separator

Terence Parr parrt at cs.usfca.edu
Thu Jul 31 15:35:58 PDT 2008


On Jul 31, 2008, at 2:08 PM, Roman Odaisky wrote:

> Greetings,
>
> Having gotten StringTemplate to work with Django, I wanted to make a  
> list of
> certain data.
>
> If I write something like
>
> $[obj.color, obj.size, obj.volume]; separator=" | "$
>
> I get
>
> Yellow | Large | 42
>
> as intended. But then I wanted to modify the presentation of one of  
> the
> attributes, namely, to append the unit to the number. I tried using
> obj.volume:{$it$ m³} and that didn’t work, neither did anything else I
> attempted.

ST might not allow arbitrary expressions within the list constructor  
[...], although that doesn't sound like something I would miss. Did  
you try obj.volume:{x | $x$ units} ?

> What is the right way to include the result of template application  
> to a list?
>
> Or, say, I want to achieve the same thing this template does:
>
> A=$a$, B=$b$, C=$c$, D=$d$
>
> except if any of a, b, c or d attributes are null, their entries  
> must not be
> shown, like this:
>
> A=1, B=2, D=4

You'd have to put $if(a)$A=$a$$endif$ and so on.

> Is there a way to construct a list from constant strings in the  
> template? If
> there were such a list, I would have written
>
> $["A", "B", "C", "D"],[a, b, c, d]:{ k, v | $k$=$v$}; separator=", "$
>
> Indeed I’ve just checked after having written this, and this exact  
> notation
> worked, much to my surprise as it doesn’t seem to be documented  
> anywhere.
> Though it doesn’t solve the problem completely: if an attribute from  
> the
> second list is null, the corresponding item from the first one isn’t  
> removed.

Right.  ST assumes that the parallel lists have the same size.

You could make or pass in a map that mapped iteration to units:

units ::= [
	"1" : "A",
	"2" : "B"
	...
]

and then do units.(i) inside an iteration where i is an implicitly  
maintained loop iteration variable. Naturally, the solution is icky.

Try:

$["A", "B", "C", "D"],[a, b, c, d]:{ k, v | $if(v)$$k$=$v$$endif$};  
separator=", "$

Ter


More information about the stringtemplate-interest mailing list