Is it possible to use tal:conditions in a javascript file?

I have some tal:conditions that are checking against ContextMenu items ID's in a HTML file. I am replacing the old context menu with a more accessible one. Problem is I think I need to create tal:conditions in my JS file where the menu is being built. Is there a way to do that?

JoshT via Plone Community wrote at 2022-8-15 16:45 +0000:

I have some tal:conditions that are checking against ContextMenu items ID's in a HTML file. I am replacing the old context menu with a more accessible one. Problem is I think I need to create tal:conditions in my JS file where the menu is being built. Is there a way to do that?

The interpretation of tal:condition requires a TAL interpreter.
Usually, no TAL interpreter is involved in the processing of JS files.

However, you can use a PageTemplate to generate JS.
If you do this, you can use tal:condition in those templates.

Why do you think you need that?

If you (really) do, you can do it the way Dieter said, and it should also be possible to use variables.

So in your 'template.pt'

<some html here>
<script tal:condition="some condition">
 Some js or Jquery or whatever here 
 and something similar to

settings: {
          slidesToShow: ${view/slides|None}
} 

 more script
  
</script>

You can do the same with 'style', maybe something like:

    <style tal:condition="view/data/height|None">
      #something-${python: view.id} img  {
        height: ${view/height}px;
        object-position: ${view/position-x}% ${view/position-y}%;
        }
    </style>

Similarly, you can use data- attributes in HTML elements, and query them from JavaScript. E.g:

<div id="my-div" data-foo="${view/get_foo_value}">
 Some content...
</div>

<script>
if ($("#my-div").data("foo") == "bar") {
  do_something();
}
</script>
2 Likes

Good idea, have never though about that

1 Like

Thank you!