1

apologies if this has been asked, I don’t seem to be able to find the solution.

What is the correct way to call craft.app.session.set in a Twig template (or any other setter function for that matter)? I can’t find a working example in the docs for anything other than getters.

To expand, this causes an error:

{# grab initial value, it is empty #}
{% set mySession = craft.app.session.get("mySession") %}
{{ "mySession = #{mySession}" }}

{# set value to 'someValue' - this will cause the error #}
{% craft.app.session.set("mySession", "someValue") %}

{# grab value again, it should now be 'someValue' #}
{% set mySession = craft.app.session.get("mySession") %}
{{ "mySession = #{mySession}" }}

However this works as expected:

{# grab initial value, it is empty #}
{% set mySession = craft.app.session.get("mySession") %}
{{ "mySession = #{mySession}" }}

{# set value to 'someValue' #}
{% set somePointlessVariable = craft.app.session.set("mySession", "someValue") %}

{# grab value again, it’s now 'someValue' #}
{% set mySession = craft.app.session.get("mySession") %}
{{ "mySession = #{mySession}" }}

Surely I don’t need to create some pointless variable just to use the setter function?

3

I'm curious to know your use case for this, but have you tried using Twig's do tag?

https://twig.symfony.com/doc/2.x/tags/do.html

i.e. {% do craft.app.session.set("mySession", "someValue") %}

1
  • Thanks, clearly it’s the Twig docs I need to spend more time in.
    – Mitrol
    Aug 24 '20 at 18:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.