With the Pro version of Snippets, you can pass "variables" to the {snippet}
tag that can make your snippet more dynamic.
This allows you to use one snippet that will generate a different output depending on what you pass along in the tag.
Then in the text of the Snippet, you can put placeholders for those variables with %myvariable%
.
Creating Variables J4
Variables in the Joomla 4 version of Snippets work a little differently compared to the Joomla 3 version.
In the Joomla 4 version of Snippets, you now first have to define the variables you want to use as part of the Snippet. This allows you to have control over the variables you want to use and helps to avoid conflicts with other extensions (such as Articles Anywhere).
When creating or editing a snippet, you can add your desired variables under the "Variables" tab. For each variable, you can define:
Variable Key | The variable key name, used in the variable placeholders and in the snippet tag as the attribute name for it. |
Default Value | Set a default value to be used when the variable is not defined in the snippet tag. |
Insert in Tag | Select to have the editor button insert this variable key as an attribute in the snippet tag. |
Text of the Snippet
Let's say you defined a year
and a company
variables under the "Variables" tab.
Now, for example, in your copyright
Snippet, your Snippet text could look like:
%year% - %company% - All rights reserved
Placing the Snippet
And then, in an article, you can pass along the two variables via the tag, like this:
{snippet alias="copyright" company="My Company" year="2019"}
Output Result
{snippet alias="copyright" company="My Company" year="2019"}
{snippet alias="copyright" company="Another Company" year="2015"}
Default variable placeholder
When defining a variable, you can also enter the "Default Value" placeholder for when a variable is not passed via the snippet tag
For example, say that you set the year
variable to 2021 by default. You would then be free to omit the year
variable from the snippet tag.
And you would get this result, with the year defaulting to 2021:
{snippet alias="copyright" company="My Company"}