How to assign local variable in Jquery template

399 Views Asked by At

Below, I am trying to print replaced items using Jquery template. There I want to set a variable partHasBeenReplaced which later I can use to print the label and close the <span> element.

  1. How can I set variable there?
  2. How to find the last element of type "REPLACEMENT"? it may not be the last element of the array.

                {{each(i,ref) productReferences}}
                        {{if ref.referenceType == 'REPLACEMENT'}}
                            {{partHasBeenReplaced = 'true'}}
                        {{/if}}
                {{/each}}
    
                {{if partHasBeenReplaced == 'true'}}
                    <span class="text-danger font-weight-bold pt-2">
                        This item has been replaced with:
                {{/if}}
    
                {{each(i,ref) productReferences}}
                        {{if ref.referenceType == 'REPLACEMENT'}}
                            {{= ref.target.code}} ,
                        {{/if}}
                {{/each}}
    
                {{if partHasBeenReplaced == 'true'}}
                    </span>
                {{/if}}
    
2

There are 2 best solutions below

3
Ashvin777 On

In order to assign data to an element using such templates, it better to use attributes. We can access create/update/remove attribute using JavaScript.

For an example, if you want to add a data for <span> then you can do it using -

<span id="mySpan" class="text-danger font-weight-bold pt-2" partreplaced="{{partHasBeenReplaced}}" ></span>

It can be accessed in JavaScript using below method -

let span = document.querySelector("#mySpan");
let partreplaced = span.getAttribute('partreplaced');

console.log(partreplaced); //will print which was set in that attribute using the templating engine.

0
HybrisHelp On

There is no simple solution to set the local variable as we do in JSTL. So what I did is I have used JS to populate final flag like partHasBeenReplaced and set it to data before passing it to Jquery template. So that I can directly use the variable in the template.