简体   繁体   中英

Including a PHP file inside a jQuery statement within a Smarty template

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}

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

Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM