9

So, I've been struggling with this for a while, trying to figure out how to get it to work. Here is what I originally did:

<button class="btn btn-primary {!v.isLink1 ? 'active' : ''}">

And so on. Here's the documentation on it. Example Expressions

However, when you actually try to save this in the developer console, you get the error:

Field Integrity Exception: Failed to save undefined: Cannot mix expression and literal string in attribute value, try rewriting like {!'foo' + v.bar}: Source

I finally figured out that you have to put all of the classes inside of the expression, like so:

<button class="{!v.isLink1 ? 'btn btn-primary active' : 'btn btn-primary'}">

This doesn't seem very intuitive. It's also not documented anywhere I could find. Could someone explain to me why it is this way and if it will ever change?

(and hopefully this question saves someone some headaches in the future)

  • 2
    You could at least make it slightly more efficient with {!'btn btn-primary' & v.isLink1 ? 'active' : ''}. – Adrian Larson Mar 27 '15 at 22:11
  • That's true, good note. That wouldn't make it nearly as bad. It still seems weird to have to do it at all though. – Anthony F. Mar 27 '15 at 22:14
  • I'll add it as an answer just in case you don't get anything more satisfactory. – Adrian Larson Mar 27 '15 at 22:16
  • Sadly, this doesn't actually work. See my comment to the answer you posted. – Anthony F. Mar 30 '15 at 20:49
4

It works this way

<button class="{! 'btn btn-primary' + ' ' +  (v.isLink1 ? 'active' : ' ' )}">

OR

<button class="{! 'btn btn-primary' + ' ' +  if(v.isLink1,'active','')}">

the whole attribute value has to be within an expression "{! ...}" Note that the strings have been concatenated with a + sign.

5

You could make it slightly more efficient like so:

{!'btn btn-primary' & v.isLink1 ? 'active' : ''}

As for why that is not allowed, I am also at a loss to explain.

  • I'd wager that aura doesn't support it. Other frameworks do, so it's kind of odd, but that's kind of salesforce-y. – sfdcfox Mar 29 '15 at 6:14
  • 1
    So, I thought this was great. Then I went and actually tried to implement it, but it doesn't work: I get an error that says Message: The entity name must immediately follow the '&' in the entity reference.: Source So, sorry, this didn't actually help. For reference, I tried removing the spaces around the & but it throws a different error. I then tried to change the & to a + and that doesn't work either. – Anthony F. Mar 30 '15 at 15:36
  • 2
    As a note, I liked this syntax too so did some digging: this does work if you replace & with &amp;, although this does reduce the neatness somewhat – nicstella Dec 12 '16 at 20:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.