MODX Community

How to define (global) variables for snippets

I want a chunk executed on every webpage except the login page.
I could do this with a snippet checking the state of a variable.
What I don’t know is where and how to define this variable.

1 Like

Ok, its pretty easy just to use a special template for the login page, and put the snippet into the regular template that would fire on every page load.

The special login template just means it doesn’t have the snippet…that’s probably the easiest way.

Modx have template variables (TVs) to hold data…but there is a lot of flexibility as to how you might approach a need. Also, I am not a dev and have trouble talking in super general terms, because I don’t know what people mean.

Could you tell us more about what you need?

Could do it without a snippet by doing it like this:

[[[[*id:ne=`5`:then=`$YourChunk`:else=`- do nothing`]]]]

If you do want the snippet, you can check against $modx->resource->get('id').

1 Like

Variables could be so many things, like you could gather data about the users and send different data to them, like for instance region or language used.

Another common one could be using a form, so the current user or a registered user could select a value, which would lead to them getting different data. So for instance the form could be right with login and run after, as a posthook perhaps, then the value would be set for the session.

Thanks for your prompt answers!
MarkH’s 1-liner ist the most compelling solution, but I’ll play with the other solution as well - just to learn more about the possibilities of ModX

1 Like

The snippet version would look like this:

(where you want the chunk to appear)

[[!MySnippet]]
/* MySnippet code */
return $modx->resource->get('id') == 5? $modx->getChunk('myChunk') : '';
1 Like

I have one additional question:
Where do I find the documentation about the short-hand writing of if-statement you use with the ‘?’ and ': ‘’ ’ in your one-liner snippet?

1 Like

What Bob posted is called a ternary operator (second section on this page), also explained here.

1 Like

It’s often written like this, which makes it a little easier to read:

/* MySnippet code */
return $modx->resource->get('id') == 5 
    ? $modx->getChunk('myChunk')   
     : '';                                                 

It’s the equivalent of this:

/* MySnippet code */
if ($modx->resource->get('id') == 5) {
    return $modx->getChunk('myChunk');
} else {
     return  '';
}
1 Like