Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use TAL:defined variable in javascript

I'm creating a page template for a plone-based website. I've defined some variables using the template attribute language:

<tal:macro metal:define-macro="sample" tal:define="var python: here.getThisVar();">

Now I would like to use var in an extern javascript file, that I call by clicking a button inside my template. How can I transfer my variable, that I can work with it in my javascript file?

like image 326
tsabsch Avatar asked Dec 07 '22 04:12

tsabsch


2 Answers

In your template define a javascript variable by writing it out using TAL like this:

<script type="text/javascript" tal:content="string:var MY_VAR=${view/myVar};"></script>

Now MY_VAR should be available in scope of your external js as long as you call it after the line above...

like image 190
Aaron Williams Avatar answered Dec 08 '22 17:12

Aaron Williams


Another way: inject your variable into HTML using an HTML 5 data attribute::

<div id="myVar" tal:attributes="data-myVar python:here.getThisVar();">

Then read it using JAvaScript/jQuery::

$('#myVar').data('myVar');
like image 33
keul Avatar answered Dec 08 '22 17:12

keul