0
How can I assign a JS function to a list of tag that are generate with a loop in HTML
Hello, I have a loop in my twig file : {% for child in listPositionRobot %} <h2 class=" accordion__items active" id="idbot"> Luna {{ child.getRobotName() }}</h2> {% endfor %} I would like to assign a JS function to all the h2 that are generate with this for loop. How can I do that ? Thank you.
5 Réponses
+ 2
You need a templating engines, some common templating engines are mustache.js , ejs.js, handlebars.js or underscore.js
Siyam Here are the solutions to use different templating engines to achieve what you mentioned:
https://code.sololearn.com/Wgvl8848NL61/?ref=app
https://code.sololearn.com/WseuLrO5LaXB/?ref=app
https://code.sololearn.com/WviFXGEw95op/?ref=app
https://code.sololearn.com/WsHD6x4039N0/?ref=app
More information:
https://github.com/janl/mustache.js
https://ejs.co/#docs
https://handlebarsjs.com/guide/#what-is-handlebars
https://underscorejs.org/#
To find more templating engines here: https://www.google.com/amp/s/colorlib.com/wp/top-templating-engines-for-javascript/%3famp=1
0
Thank for your answer.
According to your advice, if I do this :
let h2 = document.getElementById("idbot");
h2.addEventListener("click", linkToMarker);
function linkToMarker() {
document.getElementById("idbot");
//do something
}
linkToMarker();
Is this suppose to works ?
0
Siyam After I have tried out Twig templating engine, I think I finally got what you meant by "assign a JS function to all h2".
For all of the templating engine I have tried (mustache, ejs, handlebar, underscore and twig), I found that we can't assign JS function to all the template script, it only accepts object constant output, the JS function would not just be executed at all after it forms the html codes.
However we can get around the issue by assigning the JS function to the object value.
for example, instead of setting getRobotName() to the template directly, we can set a getRobotName object and set the object as
{getRobotName: getRobotName()}
Check out the example here
https://code.sololearn.com/WZ6Lz3y5P3CR/?ref=app
If you really want to run the JS function directly from the HTML element, the only way I can think of is to use React.js with jsx as templating.
I apologize for I could not understand your question previously, I hope this time I can get it right then.