2
votes

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.

1

1 Answers

3
votes

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>