TYPO3 pass Fluid variable value to the Javascript

Denis Milosavljevic picture Denis Milosavljevic · Dec 13, 2016 · Viewed 10.1k times · Source

In a fluid template I have a fluid variable which value I would like to use in my JavaScript code.

I am using JavaScript inside of fluid template.

My Code:

<!-- value I would use further in my javascript -->
<h1 id="product-model">{product.model}</h1>

<!-- Javascript code (in the same file) -->
<script>
   <![CDATA[
     function printProductWindow() {
       document.title = document.getElementById("product");
       window.print(); 
     } 
   ]]>
</script>

Thanks in advance! Denis

Answer

Ren&#233; Pflamm picture René Pflamm · Dec 13, 2016

Your element id is wrong:

 document.title = document.getElementById("product-model");

because you have defined it as id="product-model".

Alternative, if your JavaScript is in your FluidTemplate, you can also set the Value there:

<script>
  <![CDATA[
    function printProductWindow() {
      document.title = "]]>{product.model}<![CDATA[";
      window.print(); 
    } 
  ]]>
</script>

But let me warn you: changing the title via JavaScript is not a good practice.

Have an look at the TitleTagViewHelper from the news extension here to see one solution how this can be solved.