0

I'm using the Rain.tpl templating engine for my website. I now have a variable ($username) which I can use in my regular html file with {$username}. This works fine.

I now want to use this same variable in a separate .js file which I load into the thml file using <script src="/js/MySeparateJsFile.js"></script>. I tried using {$username} in it, but that doesn't seem to work. So I thought of setting it from within the html file using Javascript, but I have no clue how I would be able to do that.

Does anybody know how I can insert a javascript variable from within an html file into the .js file methods? All tips are welcome!

kramer65
  • 50,427
  • 120
  • 308
  • 488

4 Answers4

1

In Rain.tpl file declare the username as a js global variable like window.username. Use this global variable in MySeparateJsFile.js file

Rain.tpl

<script>
window.username = "{$username}";
</script>

js file

var username = window.username;
Manibharathi
  • 945
  • 6
  • 18
0

In your html file, right below code:

<script> var username= "{$username}";</script>

Now the variable username will be accessible in your js file

David John
  • 280
  • 3
  • 9
0

Only .php files will be processed and executed by default. Typically you would output any variables into the template as JavaScript variables, so that they are accessible by all external JavaScript files.

If you have multiple variables, the best way to do this is it JSON encode them on the PHP side, and output the raw result into JavaScript:

<?php
$user = array('username' => $username, 'userId' => $userId);
$userJson = json_encode($user);

In the template

<script>
    var user = {$userJson};
</script>

Note when outputting JSON via a template engine, you must ensure that it is outputting the raw data, and not using any filter (such as htmlspecialchars()).

Now, in the external JavaScript or any on page JavaScript you can access the variables:

console.log( user.username );
console.log( user.userId );

The JSON encode method solves two problems:

  • Prevents XSS vulnerabilities because any malicious content will be escaped by the JSON encoding engine.
  • The possibility of grouping lots of variables, or using a namespace for your application.
MrCode
  • 63,975
  • 10
  • 90
  • 112
0

add a data attribute to your script

<script id="myscript"  data-username="{$username}" src="/js/MySeparateJsFile.js"></script>

and access it from your javascript:

var username = document.getElementById("myscript").getAttribute("data-username");
Omar Sedki
  • 608
  • 6
  • 14