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

3

8

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?

Northcliffe answered 17/9, 2010 at 11:17 Comment(0)
N
5

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.

Northcliffe answered 17/9, 2010 at 12:16 Comment(0)
D
3

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'"
Donahoe answered 26/7, 2011 at 1:10 Comment(0)
T
0

in PHP:

<div id="contentCenter" tal:attributes="id 

php:isset(variable)&&isset(variable.property)?'IDVALUE':NULL">
Tasse answered 10/5, 2013 at 10:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.