0

I'm working with a template in Craft 2, and in referencing Twig variables in the Javascript, they are not recognized when the page is previewed. I get a Template Error - Variable x does not exist

Initially, I constructed the Javascript function by referencing the Twig variables defined earlier in the template like this (below). I got the error message that the Twig variable referenced here (myText) does not exist:

{%set myText=entry.body.getPage(1)|e('html')%}
{% set myJs %}
function myFunction(btn) 
{
    var FullText='{{myText}}';
}
{% endset %}
{% includeJs myJs %}

When I got the template error, I changed it to this (below), which gave the error that the variable reference here (entry) does not exist.:

{% set myJs %}
function myFunction(btn) 
{
    var myText='{{entry.body.getPage(1)|e('html')}}';
}
{% endset %}
{% includeJs myJs %}

Does this have to do with the positioning of the Javascript in the Template's code, or could it have to do with the Twig variables somehow? Thanks for any leads.

3
  • I guess this might be a problem with entry.body.getPage(1)|e('html'). Have you tried to set mytext to something simple like "Hello World"? And could you edit Template Error - Variable x does not exist and add the actual variable name that does not exist? This would make it easier to tell what the error is. Oct 12 at 7:52
  • 1
    don't know if that's the issue but i think you're missing an {% endset %} tag?
    – Seb
    Oct 12 at 9:38
  • @Seb Thanks for the catch. I corrected the example to reflect my code, which does have the {%endset%} tag. It is giving the error message, even though the` {%endset%}` is there. @Max I've included the error above. Thanks When I put 'hello world', it did work, but stopped working when I put the Twig there.
    – buck1112
    Oct 12 at 18:47

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.