Variables

v1 and above

Variables allow you to create dynamic content within your CitronJS samples. This feature enables you to personalize the content based on user input or other dynamic data sources. Below is a step-by-step guide on how to work with variables in CitronJS.

Step 1 - Basic Sample Definitions

First, let's define a basic sample without variables. This sample simply greets the world.

(Using CitronJS)

hello_world.xml
<citron>
    <export sample="Hello World"></export>
    
    <sample name="Hello World">
        <h1>Hello, World!</h1>
    </sample>
</citron>

Step 2 - Introducing Variables

To make our greeting dynamic, we replace the static "World" with a variable named username. Variables are denoted by curly braces {}.

hello_world.xml
<citron>
    <export sample="Hello World"></export>
    
    <sample name="Hello World">
        <h1>Hello, { username }!</h1>
    </sample>
</citron>

Step 3 - Exporting Variables

Before using variables, you must declare them in the <export> tag of your sample. This tells CitronJS that { username } is a variable. Optionally, you can specify a default value that will be used if no other value is provided.

With this setup, if no username is provided, the greeting defaults to "Hello, User".

Step 4 - Using Variables in Your HTML

To utilize the variable within your sample, include the sample in your HTML as usual, but add an attribute for the variable's value.

This will render as "Hello, John". If the username attribute is omitted, the default value ("User") is used, resulting in "Hello, User".

Conclusion

Working with variables in CitronJS allows for flexible and dynamic web content. By following these steps, you can easily incorporate variables into your samples, enhancing the interactivity and personalization of your web applications.

Remember, practice makes perfect, so feel free to experiment with different variables and scenarios to fully grasp this feature.

Last updated