Writing HTML
How to write concise html markup in Jaspr.
With jaspr, you write html as part of your component tree. Each html tag (like div
, p
, img
, etc.) has an assigned method you can use (reps. div()
, p()
, img()
, etc.).
Let's look at the following html snippet:
<div>
<h1>This is a title</h1>
<p>Hello <b>World!</b></p>
</div>
Within a jaspr component, this can be represented as such:
div([
h1([text('This is a title')]),
p([text('Hello '), b([text('World!')])]),
]);
The special text()
method does not add a html tag but renders plain text inside other elements.
HTML utilities
There exist methods for the most common html tags, like div
, a
, p
, img
as well as more special tags like
video
, form
, input
and others.
If you want support for a tag that does not have such a method yet, please don't hesitate to open an issue on github.
Each method has the following signature:
Component <tagname>(List<Component> children, {
Key? key,
String? id,
String? classes,
Styles? styles,
Map<String, String>? attributes,
Map<String, EventCallback>? events,
});
In addition to these parameters some methods have tag-specific attributes, like img(src: "...")
or a(href: "...")
.
For readability, it is recommended to put the list of child components last in the parameter list:
div(id: "main", [text('Hello World')])
is more readable than div([text('Hello World')], id: "main")
.
In case of no children specify an empty list ([]
). Some tags also omit this parameter, like img
.
Finally, here are some more examples of this syntax. You can switch between the dart code and rendered html output.
p([text('This is some '),b([text('html')]),text(' content.')])
h1(styles: Styles.text(color: Colors.blue), [text('Hello Jaspr!')])
a(href: "https://github.com/schultek/jaspr", target: Target.blank, [
img(src: "https://playground.jaspr.site/jaspr-192.png"),
])
select([
option(value: 'test', [text('Select me!')]),
option(value: 'other', selected: true, [text('Or me!')])
])
progress(value: 85, max: 100, [])