Home > Software engineering >  Including a PHP file inside a jQuery statement within a Smarty template
Including a PHP file inside a jQuery statement within a Smarty template

Time:11-16

I want to include a file if the condition is applied in jQuery using Smarty templates my Code :

{literal}
<script>
      if (window.matchMedia('(max-width: 767px)').matches) {
    // here is the include file
    {include= file.tpl}
        }
</script>
{/literal}

CodePudding user response:

I have good news and bad news. First, the bad news: This code as it is will never work, because your Smarty template has been already evaluated on the server in order to generate HTML and send it out to the browser and your Javascript code will only be evaluated once the request has responded to the browser. So, the {include= file.tpl} will be generated into your HTML, specifically into your script tag, yielding unwanted results.

The good news is that the issue is solvable. The solution can be to

Generate your literal HTML and hide it by default

In which case you can change the display CSS attribute of your literal template(s) if the condition is met.

Or, you can just POST for the literal when you need it

If the JS condition is true, then you can send an AJAX post to the server which would answer with the template.

Finally, you can use media queries

If this is only about styling, then you can use [media queries][1].

You can also use the media attribute of your link tag to load the right stylesheet. [1]: https://www.w3schools.com/css/css_rwd_mediaqueries.asp

  • Related