[antlr-interest] Getting foreach working with StringTemplate for C#
Christopher Brown
chris77550 at gmail.com
Mon Mar 3 01:04:51 PST 2008
Hi Michael,
Thankyou for taking the time to explain this to me. I did try the
wiki but got misled (deadlines, deadlines, ...) by the "foreach"
example. If it had been clearer that it was a "don't do this" code
snippet, followed by "here's how it's done in string template"
example, or if I'd had as much time as I'd've liked to read the doc
and explore the API, I suppose I'd've got it right by myself :-( It
was only when I looked once again at the "multi-valued attribute"
section of the documentation that I figured out that that was where
"looping over collections/arrays" was covered.
It's both interesting and confusing therefore that the two syntaxes
below produce the same result:
$my_collection:my_item_template()$
$my_item_template(my_collection)$
The first just seems strange, the second seems more like functional
programming. Is there a "better" way (of the two) or some things one
syntax can do that the other can't ?
Anyway, thanks again for taking the time to help me. It's sincerely
appreciated!
- Christopher
On 01/03/2008, Micheal J <open.zone at virgin.net> wrote:
> > Hi,
> >
> > I'm still struggling with StringTemplate for C#, having
> > looked through the lists, searched the web, and looked at the
> > source code.
>
>
> Did you try the wiki?
> http://www.antlr.org/wiki/display/ST/StringTemplate+Wiki+Home
>
>
> > I can't get the following working (much simplified version of
> > what I'm trying to achieve):
> >
> > string tpl = "$foreach f in foo$ $f$ $end$";
> > //string tpl = "$foo$";
> >
> > StringTemplate st = new StringTemplate(tpl);
> > st.SetAttribute("foo", new string[] {"a", "b", "c"});
> > Console.Out.WriteLine(st.ToString());
> >
> > If I switch the comment onto the first line, I get the array
> > collapsed into a string with no separators.
> >
> > In my "real" scenario, which works with simple values, I just
> > can't merge in arrays, lists, or anything enumerable. I hope
> > I'm doing something wrong -- that someone can explain to me
> > -- because it seems such a basic task, I have trouble
> > believing that it isn't implemented...!
> >
> > In the "real" scenario, I've also tried with group files and
> > varying "dollar" and "angle bracket syntaxes", with no luck.
> >
> > Can anyone help?
>
>
>
> Sure. The template text you are supplying is NOT valid ST syntax. See
> [http://www.antlr.org/wiki/display/ST/Five+minute+Introduction] for a basic
> ST introduction (the basic syntax cheat sheet is useful for beginners)
>
> Rather than:
>
>
> $foreach f in foo$ $f$ $end$
>
>
>
> Try (either of) these instead:
>
> $foo:{f| $f$ }$
>
> OR
>
> <foo:{f| <f> }>
>
>
>
> Micheal
More information about the antlr-interest
mailing list