2

I am trying to generate a html select element with one option preselected. I am unable to think of a way to do this with stringtemplate.

If user.choice is set to "B" then I want to print an html select element with option B preselected.

user.choice = "B";
StringTemplate myPage = group.getInstanceOf(....);
myPage.setAttribute("user", user);

on printing the template should generate:

<select>
    <option value="A"              >A Selected</option>
    <option value="B"  SELECTED    >B Selected</option>
    <option value="C"              >C Selected</option>
    <option value="D"              >D Selected</option>
</select>

Can someone tell me how to write the template for doing this. The number of choices (A,B...) is fixed (known at time of writing template).

This is a pretty common requirement when generating html pages for websites. But nothing like a comparison operation for passed values seems to be available in stringtemplate. Am I missing something obvious?

I am using stringtemplate group (.stg) files so solutions that have templates referencing other templates are fine. Using stringtemplate 3.2.1 in java. Using "$" delimiter instead of the now default "<>" to make html generation easier.

sundoe
  • 41
  • 1
  • 3

1 Answers1

3

StringTemplate enforces a very strict separation between your view and model. It doesn't support doing conditional operations on anything other than boolean values. I think the engine really wants you to have done the computation before you pass the data off to be rendered.

I'd suggest storing the value with the actual list items themselves. Say you already have a "value" and a "text" property on the "list" object (which are stored in your collection), you could add a selected boolean property to the list item as well. You could then use it as follows:

<select>
$list:{ l |
<option value=$l.value$ $if(l.selected)$selected="selected"$endif$>$l.text$</option>
}$
</select>
Ian Robinson
  • 16,892
  • 8
  • 47
  • 61
  • Here is a related question: http://stackoverflow.com/questions/4195828/stringtemplate-compare-strings-does-not-work – Ian Robinson Mar 26 '11 at 06:15
  • @ian-robison I appreciate that Strict separation is the better part of stringtemplate. The use case looked common so I thought there might be an established technique/pattern for it, seems there isn't. – sundoe Mar 26 '11 at 15:32
  • 1
    I believe there is an established pattern for this, and it's getting the model how you like it before mashing it up with the template. Maybe you were looking for an established exception to the rule? :) – Ian Robinson Mar 26 '11 at 15:37