4

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?

3 Answers 3

8

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...

Sign up to request clarification or add additional context in comments.

Comments

4

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');

3 Comments

Thanks for your good answer! I'm sure it works, but unfortunately i have to work with an old plone system, which doesn't support HTML5. But I will keep it in mind for my next project :).
You can use HTML 5 even on old Plone, the only difference is in the jQuery version you have (can be 1.2 or 1.3). Change change the JS to: jq('#myVar').attr('myVar');
Sorry, can't edit my last comment. The real code is jq('#myVar').attr('data-myVar');
3

There are a variety of ways to do it. All involve constructing Javascript code as if it's text, then returning the result for insertion into a page or rendering as a JS resource in the javascript registry.

If you'd like a robust example that includes provisions for message translatability and works with the JS resource registry, see the way Plone itself does it: https://github.com/plone/Products.CMFPlone/blob/4.2.7/Products/CMFPlone/browser/jsvariables.py

1 Comment

I love the example straight from CMFPlone. I think the consensus is using tal:content to define and set js variables, then adding static js code that uses those vars. I personally create a namespace (js object) for this stuff to avoid collisions: tal:content="string:var Plone.myVar = 'foo'"

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.