2

I have a smarty array

$promoFormData  Smarty_Variable Object (3)
                        ->value = Array (1)
                            deliveryDates => Array (3)
                                 0 => Array (2)
                                      startDate => "2013/06/05"
                                      endDate => "2013/06/28"
                                1 => Array (2)
                                      startDate => "2013/07/05"
                                      endDate => "2013/07/28"
                                2 => Array (2)
                                      startDate => "2013/08/05"
                                      endDate => "2013/08/28"

I want to use this array deliveryDates as available dates in datepicker. So trying to convert the above as the following Javascript array

var ranges = [ { start: new Date(2013, 06, 05), end: new Date(2013, 06, 28) },
               { start: new Date(2013, 07, 05), end: new Date(2013, 07, 28) },
               { start: new Date(2013, 08, 05), end: new Date(2013, 07, 28) } ];

I have tried using below code:

 <script>
    var js_array = new Array();
    {{foreach from=$promoFormData.deliveryDates item=array_item key=id}}
        {{foreach from=$array_item item=sub_array_item key=index}}
            js_array['{{$id}}']['{{$index}}'] = '{{$sub_array_item}}';
        {{/foreach}}
    {{/foreach}}

    console.log(js_array);
</scirpt>

And I am getting the below error

     TypeError: js_array[0] is undefined
     js_array['0']['startDate'] = '2013/06/05';

Anyone please guide me to the right way.

4

1 回答 1

7

If your Smarty security settings allow it (specifically, it is in $php_modifiers), you could use PHP's json_encode function:

var js_array = {$promoFormData.deliveryDates|json_encode};

Since JSON is a strict subset of actual JavaScript object literal syntax, this should give you a valid JS declaration.

于 2013-05-31T01:24:37.943 回答