Variable passed from PHP to Smarty and to Javascript

I have an object in php, which is passed to Smarty like $smarty->assign('o',$o) Then I need to access that object and it's properties in javascript.

How do you do it, without having any javascript in tpl. i want them all in an external file.

If not possible, how to do it?

Answers:

Answer

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>
Answer

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}
Answer

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

Answer

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}";
Answer

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

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.