简体   繁体   中英

mthaml processing my php variables inside :javascript

I'm using a PHP port of MTHAML which uses the exact same syntax. How can I tell MTHAML to not touch my variables when I use them inside

https://github.com/arnaud-lb/MtHaml

For instance this

  :javascript
      if (#{$response)} !== "") {
        show_error("#{$response}");
      }

Gets converted to this

  <script type="text/javascript">
  //<![CDATA[
      if (<?php echo htmlspecialchars(escape("$response"),ENT_QUOTES,'UTF-8'); ?> !== "") {
        show_error("<?php echo htmlspecialchars($response,ENT_QUOTES,'UTF-8'); ?>");
      }
  //]]>
  </script>

So my PHP boolean variables show up as blank in the rendered javascript, or if my php variable is a string with quotes, the quotes end up being converted to &quot.

The auto escaper is not aware of the context (html, js, etc). And unfortunately you can't disable it in #{} interpolations.

Something you could do is to expose your php variables as html data-attributes:

#data(data-response=$data)
:javascript
    var response = $("#data").data("response");
    ...

Alternatively, switch to MtHaml/Twig instead of MtHaml/PHP. Twig auto escaper is more powerful.

- autoescape true js
    :javascript
        if ("#{response}") { // response is escaped in javascript mode

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