Grzegorz
Grzegorz

Reputation: 3608

Generation a definition of a multi-dimensional array in javascript using smarty

Sorry, but I'm not JS master and tbh I'm completly clueless on this one. How can i generate multidmensionall array using smarty in javascript output.

var kreator_elements = new Array();

{foreach $kreator_elements as $element}

if(!kreator_elements[{$element->id_atrib}] instanceof Array)
    var kreator_elements[{$element->id_atrib}] = new Array();

kreator_elements[{$element->id_atrib}][{$element->id}] = new Array();
kreator_elements[{$element->id_atrib}][{$element->id}]['u_img'] = '{$element->getImageLink()}';
kreator_elements[{$element->id_atrib}][{$element->id}]['u_ico'] = '{$element->getIconLink()}';

{/foreach}

tried few approaches, with [] etc. None of them work for me for now. Always get some kind of error in console.

Upvotes: 0

Views: 160

Answers (1)

SWilk
SWilk

Reputation: 3464

Try building the associative array in pure PHP, not using Smarty:

$tmp = array();
foreach ($kreator_elements as $element) {
    $tmp[$element->id_atrib][$element->id] = array(
        'u_img' => $element->getImageLink(),
        'u_ico' => $element->getIconLink()
    );
}
$kreator_elements_json = json_encode($tmp);

Make suere that all strings are UTF-8 encoded, or the json_encode will fail. If not, run iconv() on each non unicode string.

The result can be echoed as it is correct javascript object and no smarty is needed.

Always try to use as little languages as possible when building one language in another one. If you really have to, then remember to escape each string, as just one ' sign or a newline could cause syntax error in the generated code.

Upvotes: 1

Related Questions