Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I conditionally add an id attribute in TAL (PHPTAL)?

I'm creating a form elements template file in PHPTAL. I would like to be able to OPTIONALLY pass in an id attribute for a field...

So far the code looks like this:

<xml>
  <tal:block metal:define-macro="text">
    <label tal:condition="php: !isset(hideLabel) || isset(hideLabel) && !hideLabel">${field/label}</label>
    <input name="${name}" type="text" value="${field/value}" />
    <p tal:condition="exists:field/error">${field/error}</p>
  </tal:block>
</xml>

This works as advertised. What I'd like to add is something, like

<input name="${name}" tal:attributes="id exists: id $id | $name" value="${field/value}" />

to allow me to optionally pass in an id from the METAL call...

Should I be doing it differently? I've tried using PHP: isset(id) ? $id : NULL and variations thereof, but just end up with an id="0" in the resultant HTML.

Any ideas?

like image 867
Dycey Avatar asked Sep 17 '10 11:09

Dycey


2 Answers

In case anyone else needs it, one working answer is:

<xml>
  <tal:block metal:define-macro="text">
    <label tal:condition="not: exists:hideLabel">${field/label}</label>
    <input name="${name}" tal:attributes="id id | nothing" type="text" value="${field/value}" />
    <p tal:condition="exists:field/error">${field/error}</p>
  </tal:block>
</xml>

Where passed in variables are id, name, an array named field, and hideLabel .

Note, that I've also managed to simplify the label test to something which I believe is more idiomatically TAL.

like image 155
Dycey Avatar answered Nov 09 '22 03:11

Dycey


Set VAR at a DIV containing the soon to be used element:

div class="" tal:define="VAR context.property"
    div class="" tal:attributes="class python:'grid_8 omega' if VAR else 'grid_8 alpha'"
like image 29
nerdfiles Avatar answered Nov 09 '22 04:11

nerdfiles