Sunday, 12 March 2017

Using pug mixin arguments inside attributes using string interpolation

I'm using angular and pug, and have the following template

mixin row(label, value)
    tr       
        td 
            strong= label
        td 
            span= " + value + "

Which I'm then using like

    +row("Dates", "data.dates")
    +row("Venue", "data.venue")
    +row("Meals", "data.meals")

Which is working fine, generating the following, which angular then binds to and populates the data as expected:

<tr>
    <td>Dates</td>
    <td></td>
</tr>
<tr>
    <td>Venue</td>
    <td></td>
</tr>
<tr>
    <td>Meals</td>
    <td></td>
</tr>

But I'd like to be able to use the value parameter within attributes so I can do stuff like

mixin row(label, value)
    tr(ng-show="{value} && {value} !== ''"       
        td 
            strong= label
        td 
            span= " + value + "

with the intention that this gets compiled to

<tr ng-show="data.dates && data.dates !== ''">
    <td>Dates</td>
    <td></td>
</tr>
<tr ng-show="data.venue && data.venue !== ''">
    <td>Venue</td>
    <td></td>
</tr>
<tr ng-show="data.meals && data.meals !== ''">
    <td>Meals</td>
    <td></td>
</tr>

But I can't get this to work. I've tried a variety of different escaping techniques:

   {value}
   
   #{value}
   #
   ${value}
   $
   \#{value}
   \{value}

But nothing has worked. Can't find anything at all in the docs either.

I've come up with a few workarounds, passing the attributes in like

+row("Dates", "data.dates")(ng-show="data.dates && data.dates !== ''")

But at this point, its barely a template and I might as well just copy and paste.

So, how do I use print passed values within attributes?



via Chris Clayton

No comments:

Post a Comment