Variable passed from PHP to Smarty and to Javascript

旧城冷巷雨未停 提交于 2019-12-01 23:13:57

To combine zerkms's and Didozavar's answers, here's a reusable modifier function:

<?php

function jsify($object, $name = 'foo'){
    $json_object = json_encode($object);
    return "<script type=\"text/javascript\"> var $name = $json_object; </script>";
}

$smarty->register_modifier("jsify", "jsify");

$smarty->assign("foo", $foo);
$smarty->assign("bar", $bar);

?>

{* In Template *}
{$foo|jsify}
{$bar|jsify:bar}

{* Verify *}
<script type="text/javascript">
    // assuming you're using a browser that supports console
    console.log(foo);
    console.log(bar);
</script>

Edit: After thinking about this, it might be more consistent to make it mirror the template function {assign} with a custom function.

<?php

function assign_to_javascript($params, $template){
    // validate params values
    $name = $params['var'];
    $json_object = json_encode($params['value']);
    echo "<script type=\"text/javascript\"> var $name = $json_object; </script>";
}

$smarty->register_function("assign_to_javascript", "assign_to_javascript");

$smarty->assign("foo", $foo);
$smarty->assign("bar", $bar);

?>

{* In Template *}
{assign_to_javascript var="foo" value=$foo}
{assign_to_javascript var="bar" value=$bar}

{* Verify *}
<script type="text/javascript">
    // assuming you're using a browser that supports console
    console.log(foo);
    console.log(bar);
</script>

Nope, it is not possible. Smarty's assign method just passes data from php to templates.

You could create your own smarty function that would output necessary js and use it as modifier in your templates:

{$o|jsify}

<script type="text/javascript"> var variable = {variable}; </script>

I used the following technique and it works for me use double quote arround smarty variable(single quote is not worked in my case)

var base_dir = "{$base_dir}";

I believe I have found the solution such that ..content won't appear in the .tpl and hence html

pass the php variable to javascript variable directly in the .php , it will work, and not ...content will appear in the .tpl and html

I used following technique and it worked for me pretty well.

In test.php file.

 $t = new template();
 $t->assign("testVar", $testVar);
 $t->fetch("test.tpl");

In test.tpl file. create a div with grabMe.

    <div id="grabMe">{$testVar}</div>

    {literal}
        <script language="javascript" type="text/javascript">
              var testVar = $("#grabMe").text();
        </script>    
    {/literal}

It works fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!