tags:

views:

58

answers:

4

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, due to the dot in my array key "detailpage.var1", which for Smarty is the delimitor for the array elements. As I don't want to rewrite my config array (cause it is used in many other places), my question is:

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

+1  A: 

Maybe $smarty->assign('config', array_values($config)); and {$config[0]} instead of {$config.detailpage.var1} would do.

ghaxx
{$config[0]} would work. But I'd prefer a solution with the arrays keys, instead of indexes, cause when having 100 config-options this is much nicer to read and one could rearrange them when adding new config options.
JochenJung
I expected that kind of reply. :) There's DEFINE for replacing numbers with names but it's still not a pretty solution.
ghaxx
+1 for Define + ID idea, though its really quite a complicated workaround
JochenJung
+1  A: 

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

Naktibalda
Does not work. The [ is not allowed:Fatal error: Uncaught exception 'Exception' with message 'Syntax Error in template "index.htm" on line 32 "{$config.[detailpage.var1]}" - Unexpected "[", expected one of: "{" , "$" , "identifier" , INTEGER'I tried {$config{detailpage.var1}} as well
JochenJung
delete . before [
Naktibalda
There was no . in front of [
JochenJung
+1  A: 

You can reformat the keys in the associative array to comply with Smart Compiler Regex'es.

$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 substitute the . with a _.


Walk the array,

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

Something along those lines.

RobertPitt
Would be a good workaround to use. +1 Thanks. But I'll wait if someone will come up with a better solution before accepting it.
JochenJung
+2  A: 

Not the smartest solution but it should work:

{assign var=myKey value="detailpage.var1"}
{$config.$myKey}
Zsolti
Good idea. +1But I would prefer the workaround solution from RobertPitt, as it is automated for all variables in the $config-Array.Using yours I would have to put the assign line in front of every (first) config-variable call.
JochenJung