Templating
GreenLight includes a handful of resources to bind data to the DOM.
We'll cover the basics but you can go deeper on all directives by accessing their dedicated documentation page.
Binding Variables
If you just want to bind a variable to an element you can do that by simply adding the gl-bind
attribute.
<div gl-controller="BindController">
<p gl-bind="helloWorld"></p>
</div>
<script>
const Controller = GreenLight.controller("BindController");
Controller.$store.set("helloWorld", "Hello, world!");
</script>
As you can see, it now binds the helloWorld
variable to the text content of the p
element
If helloWorld
changes, it will automatically update the p
element as well.
gl-template
You can also use gl-template
to create more complex values with the available variables.
<div gl-controller="BindController">
<p gl-template="The variable we set in JS was {helloWorld}"></p>
</div>
<script>
const Controller = GreenLight.controller("BindController");
Controller.$store.set("helloWorld", "Hello, world!");
</script>
Bind to other properties
<div gl-controller="BindController">
<p gl-bind:style.color="bindedColor">Lorem ipsum dolor sit.</p>
</div>
<script>
const Controller = GreenLight.controller("BindController");
Controller.$store.set("bindedColor", "red");
</script>
Lorem ipsum dolor sit.
Toggle elements
If you want to toggle the visibility of an element based on some criteria, you can do so with gl-if
.
<div gl-controller="ToggleController">
<button gl-on="click:toggleVisibility">Toggle</button>
<p gl-if="shouldShow">Helloooooooo</p>
</div>
<script>
const Controller = GreenLight.controller("ToggleController");
Controller.$store.set("shouldShow", true); // Default value
Controller.on("toggleVisibility", () => {
const shouldShow = Controller.$store.get("shouldShow") ?? false;
Controller.$store.set("shouldShow", !shouldShow);
});
</script>
Helloooooooo
Keep in mind that it only swaps between display
styles in CSS, not actually removing the element.
Looping
One of the most essential things you need to do in a web app is looping over elements. In GreenLight you've got gl-for
:
<div gl-controller="LoopingController">
<p style="font-weight: bold">A list of Todo's</p>
<ul>
<template gl-for="todo in todos">
<li gl-bind="todo"></li>
</template>
</ul>
</div>
<script>
const Controller = GreenLight.controller("LoopingController");
Controller.$store.set("todos", [
"Clean room",
"Go to the gym",
"Take lunch with friends",
]);
</script>
This directive is a version of Alpine's x-for
that was adapted to GreenLight's internals because it is "field tested" and it should work as intended. Big shout out to them <3
A list of Todo's