Skip to content

Instantly share code, notes, and snippets.

@croxton
Last active April 8, 2018 02:23
Show Gist options
  • Save croxton/8865797 to your computer and use it in GitHub Desktop.
Save croxton/8865797 to your computer and use it in GitHub Desktop.
Saving user preferences with Stash + jQuery

Create a template such as site/save_preference with the following code - adjust the regex to suit your needs:

{exp:switchee variable="{segment_3}" parse="inward"}
	{!-- allow an alphanumeric name (and - or _) for the preference key only --}
	{case value="#^[a-zA-Z0-9-_]+$#"}
		{!-- allow a numeric value only --}
		{exp:stash:set name="{segment_3}" type="snippet" save="yes" scope="user" match="#^[0-9]+$#"}{segment_4}{/exp:stash:set}
	{/case}
{/exp:switchee}

Save a preference from jQuery - pass the variable name as segment_3 and the value in segment_4:

$.ajax({ url: "/site/save_preference/my_variable/1"});

If you want to use it in your template code:

{!-- load variable into memory --}
{exp:stash:get name="my_variable" scope="user" type="snippet" default="0" output="no"}

{!-- use in a conditional --}
{if my_variable}
...
{/if}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment