Smarty variables inside JS files

I understand using tpl files and variables inside such files.

Issue is how to manage variables also inside js file.
If I add JS file like the following line:

How to add also variables inside JS file. Is there good example to do this?

<script>
jQuery(document).ready(function()
{
MyfunctionJQuery.init();
}
);

In this case it will not work like tpl file

// {/literal}{$variablesmng.myvariable1}{literal}, {/literal}{$variablesmng.myvariable2}{literal}),

If you’re having that much problems with Smarty, maybe it’s better to use a template engine that does not have such problems.

PHP is server-side and jQuery client-side. When I use tpl file it will be detected smarty variable. When I insert JS file and add smarty variable it will not detect.
Another framework will not solve this but probably can be solved in some way using Smarty.

Do you have example as JS file that there are included variables? just sample…

Can you be more clear what you want to achieve? First you say you want template variables inside js files and next you show an example of an inline script in a html file. I’m confused.

Normally, you don’t use template variables in plain js files but you can pass them into js via normal html templates:

<script>
jQuery(document).ready(function()
{
MyfunctionJQuery.init('{$myvar}');
}
);
var myvar2 = {$myvar2};
</script>
<script src="external.js"></script>

If you wanted variables inside the external.js file then you could do it but you’d need to create a separate template for it and invoke it from a separate php script. However, I think in most cases it would be overkill and I would prefer to simply pass the variables through the html template like in the example above.

Will you share some more specifics? As far as I know all template engines behave the same way regarding js - it would be interesting to know what kind of js features are available in engines other than Smarty?

Thank you for your example. Sorry if it was not clear. It will solve many issues if can be done. See please real example. TPL file is using Javascript code.
In this example I have to insert PHP values due to applications.

{literal}
<script>
(function(h, o, t, j, a, r)
 {
  h.hj = h.hj||function() {(h.hj.q = h.hj.q||[]).push(arguments)};
  h._hjSettings = {hjid: {/literal}{$myvars.js_hotjar1}{literal}, hjsv: {/literal}{$myvars.js_hotjar2}{literal}};
  a = o.getElementsByTagName('head')[0];
  r = o.createElement('script'); r.async = 1;
  r.src = t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
  a.appendChild(r);
 }
)(window, document, '//static.hotjar.com/c/hotjar-', '.js?sv=');
</script>
{/literal}

Now I have to insert also server value inside pure Javascript file and many ID’s. How to solve this in real example? ID’s are values like 40.781840, -73.972967


var GoogleMapDemo = {
init: function() {

    function initialize() {
      var map;
      google.maps.event.addDomListener(window, "load", function ()
        {
          var map = new google.maps.Map(document.getElementById("map_div"),
            {
            center: new google.maps.LatLng(40.783221, -73.966143),
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP
            }
          );
          var infoWindow = new google.maps.InfoWindow();
          function createMarker(options, html) {
            var marker = new google.maps.Marker(options);
            if (html) {
              google.maps.event.addListener(marker, "click", function ()
                {
                  infoWindow.setContent(html);
                  infoWindow.open(options.map, this);
                }
              );
            }
            return marker;
          }
          var marker0 = createMarker(
            {
            position: new google.maps.LatLng(40.774462, -73.967784),
            map: map,
            icon: "markers/marker-green.png"
            }, "<h1>Marker 0</h1><p>This is the home marker.</p>"
          );

          var marker1 = createMarker(
            {
            position: new google.maps.LatLng(40.781840, -73.972967),
            map: map
            }, "<h1>Marker 1</h1><p>This is marker 1</p>"
          );

          var marker2 = createMarker(
            {
            position: new google.maps.LatLng(40.775526, -73.971721),
            map: map
            }, "<h1>Marker 2</h1><p>This is marker 2</p>"
          );
        }
      );

    }

    google.maps.event.addDomListener(window, 'load', initialize);

  }
}

This one is fine but in Smarty 3 you don’t have to use all those {literal} tags - they can make your code difficult to read. If you put a space or newline after { then you don’t need {literal}:

<script>
(function(h, o, t, j, a, r)
 {
  h.hj = h.hj||function() { (h.hj.q = h.hj.q||[]).push(arguments) };
  h._hjSettings = { hjid: {$myvars.js_hotjar1}, hjsv: {$myvars.js_hotjar2} };
  a = o.getElementsByTagName('head')[0];
  r = o.createElement('script'); r.async = 1;
  r.src = t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
  a.appendChild(r);
 }
)(window, document, '//static.hotjar.com/c/hotjar-', '.js?sv=');
</script>

Pass the php values from your html template, the same one where you include the external js file:

<script src="googleMapDemo.js"></script>
<script>
GoogleMapDemo.myLat = {$myLat};  // 40.781840
GoogleMapDemo.myLng = {$myLng}; // -73.972967
</script>

googleMapDemo.js now doesn’t need any php variables (see marker1):

var GoogleMapDemo = {
init: function() {

    function initialize() {
      var map;
      google.maps.event.addDomListener(window, "load", function ()
        {
          var map = new google.maps.Map(document.getElementById("map_div"),
            {
            center: new google.maps.LatLng(40.783221, -73.966143),
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP
            }
          );
          var infoWindow = new google.maps.InfoWindow();
          function createMarker(options, html) {
            var marker = new google.maps.Marker(options);
            if (html) {
              google.maps.event.addListener(marker, "click", function ()
                {
                  infoWindow.setContent(html);
                  infoWindow.open(options.map, this);
                }
              );
            }
            return marker;
          }
          var marker0 = createMarker(
            {
            position: new google.maps.LatLng(40.774462, -73.967784),
            map: map,
            icon: "markers/marker-green.png"
            }, "<h1>Marker 0</h1><p>This is the home marker.</p>"
          );

          var marker1 = createMarker(
            {
            position: new google.maps.LatLng(GoogleMapDemo.myLat, GoogleMapDemo.myLng),
            map: map
            }, "<h1>Marker 1</h1><p>This is marker 1</p>"
          );

          var marker2 = createMarker(
            {
            position: new google.maps.LatLng(40.775526, -73.971721),
            map: map
            }, "<h1>Marker 2</h1><p>This is marker 2</p>"
          );
        }
      );

    }

    google.maps.event.addDomListener(window, 'load', initialize);

  }
}

In this example I used the GoogleMapDemo object created earlier in the external js file and I inserted the variables to this object. But if you don’t have an object like this you can do the same with global variables, or better yet create a special object for passed variables from php just for readability:

<script>
var passedVars = {
  centerLat: 40.783221, // you can put {$centerLat} instead of the number
  centerLng: -73.966143,
  lat0: 40.774462,
  lng0: -73.967784,
  lat1: 40.781840,
  lng1: -73.972967,
  lat2: 40.775526,
  lng2: -73.971721
};
</script>
<script src="googleMapDemo.js"></script>

And in googleMapDemo.js replace your numeric values with references to this object like passedVars.centerLat, passedVars.lat1, passedVars.lng2, etc.

This way you leave your external js file a simple static file without any php or template variables - this is good for performance since loading the js file will not consume (almost) any CPU cycles.

The main problem I experienced is that you can read a perfectly fine JavaScript object as Smarty variable, due to the use of single { } as variable’s delimiters. counter example from Twig, where {{ }} are used, objects cannot be mistaken as variables.

Thank you. will test.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.