5

How can I incorporate a variable into a string, so that the result is a longer string that includes the contents of a given variable?

For example, I have a variable called apple and its value is "Arlington Pippin" (it's a type of apple). I'd like to end up with a phrase that reads:

There is an Arlington Pippin.

How could I accomplish this?

  • Yep, I like apples. – nicael Jun 18 '14 at 19:56
17

If you‘ve got a multi-lingual site (or even if you don’t), you can pass variables into strings with the |t filter:

{{ "Welcome back, {name}"|t( {'name': currentUser.name} ) }}

(See http://buildwithcraft.com/help/static-translations for details on how you can use the |t filter to translate your text.)

15

I know three ways:

  • Using format() (look for type specifiers)

    {% set string = "There is an %s."|format("apple") %}
    
  • Using string interpolation (assuming that apple="apple")

    {% set string = "There is an #{apple}." %}
    
  • Using string concatenation (assuming that apple="apple")

    {% set string = "There is an " ~ apple %}
    
  • i recommend string interpolation become the informal standard IMHO. – Luke Holder Jun 18 '14 at 2:05

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.