Smarty array with dot in key

I have an array in PHP that looks like this:

$config['detailpage.var1'] $config['detailpage.var2'] $config['otherpage.var2'] $config['otherpage.var2'] ... 

To access it in Smarty, I would do

 $smarty->assign('config', $config); 

With this template:

 {$config.detailpage.var1} 

Unfortunately, this does not work, because of the point in my key key "detailpage.var1", which for Smarty is a limiter for array elements. Since I don't want to rewrite my configuration array (because it is used in many other places), my question is:

Is there any other notation I could use that works with dots in array keys? Or can I somehow escape them?

+4
source share
5 answers

I "accidentally" found the answer to this question after I was looking for an answer for myself. In this case, I use hostnames as keys that always have periods. You can access them with {} around the dotted name. for example {$var.foo.bar.{"my.hostname.example.com"}.ipaddress} .

This escaped syntax can also be used when you need to expand a variable containing a period. for example {$var.foo.bar.{$var.bingo}}

+1
source

Not the smartest solution, but it should work:

 {assign var=myKey value="detailpage.var1"} {$config.$myKey} 
+7
source

Try using array notation {$ config ['detailpage.var1']} or {$ config [detailpage.var1]}.

+3
source

You can reformat keys in an associative array according to Smart Compiler Regex'es rules.

 $configS = array(); foreach($config as $key => $value) { $key = str_replace('.','_',$key); $configS[$key] = $value; } $smarty->assign('config', $configS); 

OR

 $configS = array(); foreach($config as $key => $value) $configS[str_replace('.','_',$key)] = $value; $smarty->assign('config', $configS); 

Now you can use {$config.detailpage_var1} instead, just replace . on _ .


Walk through the array

 function cleanKeysForSmarty(&item,$key) { return array(str_replace('.','_',$key) => $value); } $smarty->assign("config",array_walk_recursive($config,'cleanKeysForSmarty')); 

Something like that.

+3
source

Using:

{$ array ["key.with.dot"]}

Or:

{$ array ["key.with.dot"] ["subkey"]}

0
source

Source: https://habr.com/ru/post/1315633/


All Articles