Syntax guide
Props
To read props passed to a component, you can use props[:foobar]
as well as $foobar
. The latter will transform into the former,
for convenience.
Self / recursion
The constant Self
is defined to point at the current class,
which is useful if you want to make a tree.
%ul
= Dir.entries($path).map do |path|
%li[path]
%Self(path=path)
Whitespace
Here comes the biggest difference between Mayu Haml and regular Haml. Whitespace is significant in HTML in some cases, and it’s very important for the patching algorithm that the DOM and the VDOM are in sync, and every time there has been issues with it, it has been because of unwanted whitespace.
Therefore, Mayu strips whitespaces in places where regular Haml doesn’t, and the operators for inserting whitespace work somewhat differently.
All these paragraphs will turn into <p>Hello world</p>
.
%p Hello world
%p
Hello world
%p
Hello
world
%p
Hello world
If you want to include whitespace between text and elements,
you need to use the <
and >
operators.
%p
Read more on
%a(href="https://github.com/mayu-live/framework")< GitHub
\.
Notice the <
after the link.
That operator will add a space before the element.
There will be no space between the link and the dot,
because the >
operator was not used.
<
adds a space before an element.>
adds a space after an element.
Lists and keys
Mayu uses keys to identify which items have been added, changed or removed from lists, just like React does.
You can use the Object Reference syntax in Haml to specify keys. Example:
%ul
= todos.map do |todo|
%li[todo.id]= todo.text
Pattern matching
You can use pattern matching in a lot of places, and it’s encouraged,
because it verifies that structures are have the expected format.
If patterns don’t match, you get NoMatchingPatternError
,
so you will know exactly why something went wrong.
Here are some useful links:
:ruby
def self.get_initial_state(initial_count: 0, **) = {
count: initial_count
}
def handle_click(event) =
case event
in { target: { name: "increment" } }
update { |state| { count: state[:count] + 1 } }
in { target: { name: "decrement" } }
update { |state| { count: state[:count] - 1 } }
end
- state => count:
%div
%output= count
%button(onclick=handle_click name="increment")
%button(onclick=handle_click name="decrement")
Early returns
The following snippet will show a button, and once it has been clicked, the component will instead show a paragraph.
:ruby
def self.get_initial_state(**) = {
clicked: false
}
def handle_click(event)
update(clicked: true)
end
= return if state[:clicked]
%p You clicked the button.
%button(onclick=handle_click) Click me
You can also use return unless
.
= return unless $data
%p Loading…
%pre= $data