Given a metal macro that looks like this:
<tal:block metal:define-macro="foo">
<option value="1">Foo</option>
<option value="2">Bar</option>
<option value="3">Baz</option>
</tal:block>
And a template which uses the macro like this:
<select>
<tal:block tal:define="selectedValue 2" metal:use-macro="foo" />
</select>
What do I need to add to the macro, such that the resulting HTML looks like this:
<select>
<option value="1">Foo</option>
<option value="2" selected="selected">Bar</option>
<option value="3">Baz</option>
</select>
I've tried various different methods using the php:
expression and even defining my own TALES function, but nothing seems to give me what I'm looking for.
Browsers treat any option where the selected
attribute appears as actually selected. That means that selected
, selected=""
, selected="foo"
, etc. will all make the option selected. PHPTAL has a built in attribute value | nothing
syntax that resolves this, but this only falls back to nothing
in the case that value
is empty, which doesn't help me, since I need to compare it to a value. Something like this (doesn't work):
<option value="2" tal:attributes="selected (selectedValue == 2 ? 'selected' : NULL) | nothing">Bar</option>
That should suffice:
tal:attributes="selected php:selectedValue == 2"
PHPTAL knows about attributes like selected
and checked
and will convert boolean to correct value.
php:selectedValue == 2 ? 'selected' : NULL
would work as well.