javascript – How to "translate" SMARTY to JAVASCRIT or even JQUERY?

Question:

I have this code in a "Smarty template", (which runs on a Fuelphp server), I simply want to "rewrite" it in JavaScript or Jquery :

<select size="1" name="dw01">
  {section name=item start=1 loop=$item+1 step=1}
    {if $item_push}
      {foreach from=$item_push item=val}
        <option value="{$smarty.section.item.iteration}">
          {assign var="name" value="item_name`$smarty.section.item.iteration`"}
          {$val.$name|default:''}
        </option>
      {/foreach}
    {/if}
  {/section}
</select>

Answer:

Smarty is a PHP templating engine, that is, it helps you generate HTML quickly and dynamically as in the case of your example, where Smarty is generating a select form dynamically.

To do the same thing with JavaScript or JQuery there are several ways.

Pulling an object, which can be a JSON generated with PHP, using only JavaScript:

var options = '',
    //essa é a lista de onde sairão os valores das opções do select
    movie_list = {
      'The Revenant'       : 'The Revenant',
      'Deadpool'           : 'Deadpool',
      'Fight Club'         : 'Fight Club',
      "Birdman"            : 'Birdman',
      'Dallas Buyer\'s Club': 'Dallas Buyer\'s Club'
    };
//itera pela lista pra gerar as opções do select
for(var key in movie_list) {
    options += '<option value="' + key  + '">' + movie_list[key] + '</option>'
}
//inclui as opções no select de id movies
document.getElementById('movies').innerHTML = options;
<select id="movies"></select>

JSFIDLE

Pulling an object, which can be a PHP generated JSON, using JQuery:

var options = '',
    movie_list = {
      'The Revenant'       : 'The Revenant',
      'Deadpool'           : 'Deadpool',
      'Fight Club'         : 'Fight Club',
      "Birdman"            : 'Birdman',
      'Dallas Buyer\'s Club': 'Dallas Buyer\'s Club'
    };
   
for(var val in movie_list) {
    $('<option />', {value: val, text: movie_list[val]}).appendTo($('#movies'));
}
<select id="movies"></select>

JSFIDDLE 2

There are many more possibilities, it depends a lot on what you want to do and how you want to do it.

Scroll to Top