I have a problem to overwrite my JS plugin options from Twig.
My JS plugin options look like this:
static options = {
configurator: {
startTabIndex: 0,
startModel: null,
responsive: {
xs: {
startTabIndex: 1,
startModel: 1
},
sm: {
startTabIndex: 1,
startModel: 1
},
md: {
startTabIndex: 1,
startModel: 1
},
lg: {},
xl: {},
xxl: {},
},
}
}
I am trying to overwrite these options from my template.
{% set configuratorOptions = {
configurator: {
startTabIndex: 1,
startModel: 10,
responsive: {
xs: {},
sm: {},
md: {},
lg: {},
xl: {},
xxl: {},
},
}
} %}
data-product-configurator-options="{{ configuratorOptions|json_encode }}
The values startTabIndex
and startModel
are working fine, but I want to empty the responsive settings like in the example above. After the option merge my options look like this and are not working properly. I think because the type switched from object to array.
{
"configurator": {
"startTabIndex": 1,
"startModel": 10,
"responsive": {
"0": [],
"576": [],
"768": [],
"992": [],
"1200": [],
"undefined": []
}
}
}
The getSettings function is not working with this. How do I prevent the type switch?
It works when I overwrite the responsive settings with values
Works
{% set configuratorOptions = {
configurator: {
startTabIndex: 1,
startModel: 10,
responsive: {
sm: {
startTabIndex: 123,
startModel: 123,
},
},
}
} %}
But I can't empty them.
Doesn't work
{% set configuratorOptions = {
configurator: {
startTabIndex: 1,
startModel: 10,
responsive: {
sm: {},
},
}
} %}
You could solve this by passing the the following value, JSON_FORCE_OBJECT
, to the flag
parameter of the json_encode
filter
{% set configuratorOptions = {
configurator: {
startTabIndex: 1,
startModel: 10,
responsive: {
xs: {},
sm: {},
md: {},
lg: {},
xl: {},
xxl: {},
},
}
} %}
{{ configuratorOptions|json_encode(constant('JSON_FORCE_OBJECT'))|raw }}
References