-2

I am using a twig variable in a javascript file. My goal is to access the attribute of the variable with a predifined string. Basically, I want to do this:

var a = 'data-foo';
console.log( {{ attribute(foo, a) }} );

Unfortunately, this is not working but if I directly use console.log( {{ attribute(foo, 'data-foo') }} );, It works, I do get my data.

For special purposes, I need to apply the first idea. I've tried different things like:

console.log("{{attribute(foo, "+a+")}}");
console.log( {{foo[a]}} );
console.log( {{ "foo."+a }} );

but none of this is working, javascript can't find the result and I get a blank answer from the console.

Alexandre Brba
  • 118
  • 1
  • 3
  • 11

1 Answers1

2

You're trying to pass a JavaScript variable into a Twig function. This isn't directly possible.

{% set a = 'data-foo' %}
var a = '{{ a }}';
console.log( {{ attribute(foo, a) }} );

Here you will have the variable a available in both Twig and JavaScript.

James Monger
  • 10,181
  • 7
  • 62
  • 98