twigjs / twig.js

JS implementation of the Twig Templating Language
BSD 2-Clause "Simplified" License
1.89k stars 275 forks source link

Simply twig.js in a browser #711

Open playinglife opened 4 years ago

playinglife commented 4 years ago

Hi, I have spent many, many hours to try to make twig.js work in a browser. Unsuccessful :( All I want is to be able to include the twig.js file and then render some templates. I have many years of experience in development but it looks like this just got the better of me.

I do one rendering and it renders fine. Then when I'm doing the second rendering of the same template, data from the first rendering is used. The issue is in the .replace filter.

Also I tried this simple code and it's not working. I might be doing something wrong.

        var t="Are you {{ place }} at all?";
        Twig.twig({
            id: "posts",
            data: t,
        });
        alert(Twig.twig({ref: 'posts'}).render({place: 'where'}));

I include twig.min.js version 1.14.0 from here: https://asset-packagist.org/package/npm-asset/twig The code I use:

Thank you, I really appreciate any help, Daniel

playinglife commented 4 years ago

As a note: One needs to be careful when including a template especially when one also has TWIG templating on the server side. If the template is not properly added into the code then the server side TWIG engine might process it too, besides the twig.js engine. Ex: "Hello {{ name }} how are you." If this would go into a view.html.twig template file then it should be: {{' Hello {{ name }} how are you. '}} so the php twig engine would not process it.

playinglife commented 4 years ago

There might be a bug in the replace filter.

The code should display only the extension "JPG". https://jsfiddle.net/playing_life/g96u3a4j/2/#&togetherjs=9v1FN3d6ap

RobLoach commented 4 years ago

Does (front):'' actually work?

Unsure that's implemented in twig.js, but I could be wrong.

playinglife commented 4 years ago

Strangely the REPLACE works the first time but the second time looks like it still uses the data from the previous REPLACE call.

Ex: 'Text x'|replace('x','1') - this one calls the replace function with parameters "x" and "1" 'Text x'|replace('x','2') - this one calls the replace function with parameters "x" and ("1" instead of "2". always the previous value)

Might be a variable scope issue.

willrowe commented 2 years ago

This is due to a deeper issue with how expressions are parsed and tokenized. For some reason the are being resolved to static values and cached instead of being kept dynamic and evaluated on each render.