Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate strings and variables in assignment of new variable in smarty

I want to concatenate an already assigned variable and save it to a new variable, something like this:

{assign var=permCat value="de.admin"}
{assign var=objectName value="myClass"}
{assign var=objectNameUpper value=$objectName|ucfirst}
{assign var=editPerm value=$permCat|cat:"canEdit"|cat:$objectNameUpper}

So, the resulting $editPerm should be: de.admin.canEditMyClass

How can I do this? Currently, it throws an error: Cannot use string as array offset...

like image 702
F.P Avatar asked Feb 19 '12 17:02

F.P


People also ask

How do you concatenate strings and variables?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

How do you concatenate strings and variables in Java?

Using the + operator is the most common way to concatenate two strings in Java. You can provide either a variable, a number, or a String literal (which is always surrounded by double quotes). Be sure to add a space so that when the combined string is printed, its words are separated properly.

Is an operator used for concatenation and assignment of a string?

String Operators ¶ The first is the concatenation operator ('. '), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator (' . = '), which appends the argument on the right side to the argument on the left side.


1 Answers

The error you describe cannot be caused by the given code. I assume you are trying to build a string "de.admin.canEditMyClass" to use as a variable {$builtString.foo}. That's where the error occurs, because smarty does not magically convert your string to a variable reference.

If you're using Smarty2:

{assign var=objectName value="myClass"}
{assign var=objectNameUpper value=$objectName|ucfirst}
{assign var=editPerm value="canEdit"|cat:$objectNameUpper}
{$de.admin.$editPerm.foo}

If you're using Smarty3:

{$de.admin.{"canEdit"|cat:{"myClass"|ucfirst}}.foo}
like image 100
rodneyrehm Avatar answered Sep 26 '22 22:09

rodneyrehm