0

I have a set of arrays of php variables that are assigned into SMARTY template. The following is the php variable:

$smarty = new Smarty;
for ($i = 1; $i <= 3; ++$i) {
  ${'field'.$i} = array('group_rank_edit_' . $i, 'some_data'.$i);

  // Assign variable to the template
  $smarty->assign('field'.$i , ${'field'.$i});
}

So there are 3 arrays that are assigned to the template. Now, in the template I have difficulties on retrieving the values. Suppose the template is kinda like this:

{{for $i=1 to 3}}
  $().ready(function() {
    $("#group-ranks-edit-form").validate({
        rules: {
           {{$field.{{$i}}.0}}: {
                required: true,
            }
        },
     });
});
{{/for}}

So that one of the output will look like this:

$().ready(function() {
    $("#group-ranks-edit-form").validate({
        rules: {
          group_rank_edit_1 : {
                required: true,
            }
        },
     });
});

Clearly the following format doesn't result the intended output:

{{$field.{{$i}}.0}}

Any ideas? I'm using Smarty 3 BTW.

Much appreciated

1 Answer 1

2

You can store your fields in just one array (PHP) an iterate over it (Smarty) by using foreach.

PHP

$smarty = new Smarty;
$f      = [];                // array will contain data of all 3 fields
for ($i = 1; $i <= 3; ++$i)  // fill array with data
{
    $f[$i] = array('group_rank_edit_' . $i, 'some_data'.$i);
}
$smarty->assign('f' , $f);   // assign the array to smarty

Smarty

{foreach from=$f key=i item=data}
    {literal}
        $().ready(function() {
            $("#group-ranks-edit-form").validate({
                rules:
    {/literal}
                    {$data.0}:
    {literal}
                    {
                        required: true,
                    }
                },
            });
        });
    {/literal}
{/foreach}

Output generated by Smarty

$().ready(function() {
    $("#group-ranks-edit-form").validate({
        rules:
            group_rank_edit_1:
            {
                required: true,
            }
        },
    });
});

$().ready(function() {
    $("#group-ranks-edit-form").validate({
        rules:
            group_rank_edit_2:
            {
                required: true,
            }
        },
    });
});

$().ready(function() {
    $("#group-ranks-edit-form").validate({
        rules:
            group_rank_edit_3:
            {
                required: true,
            }
        },
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.