Skip to content

Template Cheat Sheet

StefansArya edited this page Oct 19, 2020 · 4 revisions

This part will give you simple example about how to implement template.

Create your model first with javascript

sf.model('modelName', function(self){
    // Write model property here
    self.hello = "world";
    self.func = console.warn;
    self.list = [1, 2, 3];
    self.obj = {a:1, b:2, c:3};
});

If you're using sf.model with name modelName then you need to write HTML inside <sf-m name="modelName"> element. But only for the mustache template you can't directly use <sf-m>{{ hello }}</sf-m>, and should be wrapped inside div or span.

Using model with template

<sf-m name="modelName">
 <!-- Write template here -->
 <div>hello {{ hello }}</div>
</sf-m>

Bind model with input element

Below should also be wrapped inside <sf-m>.

<!-- One way binding -->
<input sf-into="intoModel"></input> <!-- Value into -> model -->
<input value="{{ fromModel }}"></input> <!-- Value from <- model -->

<!-- Two way binding -->
<input sf-bind="hello"></input> <!-- Value synced with <-> model -->

Event listener

func is function name registered on your model/component scope.

<a @click="func"></a>
<a @mouseup.left="func"></a>

<!-- You can also define the parameter -->
<a @click="func('hello', event)"></a>

<!-- With control button -->
<a @mouseup.ctrl.left="func"></a>

<!-- Keyboard key must be started with UpperCase-->
<input type="text" @keyup.ctrl.Enter="func"/>
<input type="text" @keyup.ArrowUp.once="func"/> 

once, prevent, stop, passive, capture are available

<!-- Letters are case sensitive -->
<input type="text" @keyup.Z="func"/> UpperCase `Z`
<input type="text" @keyup.z="func"/> LowerCase `z`

Almost all event are supported like keyup, mousedown, touchup, scroll, etc. Addional event: taphold, gesture, dragmove, filedrop

Repeat element with array/object values

<div sf-each="val in list">
    Hello {{ val }}
</div>

---

<div sf-each="key, val in obj">
    Object[{{ key }}] = {{ val }};
</div>

Run script for/on element

If you want to use conditional on your element class/style you can use JavaScript's on the mustache {{ condition ? true : false }}.
But for more complex usage, we can use full JavaScript with enveloped template:

<div>
{{@exec
    var isChanged = (hello !== 'world');

    // This will returned as new element
    {[ <i>It was {{ isChanged ? '' : 'not' }} changed</i> ]}

    var escapedHTML = "<b>I'm not bold</b>";
    var realHTML = "<b>And I'm bold</b>";

    /* Escaped HTML, this will not become bold */
    {[ {{ escapedHTML}} ]}

    /* Not escaped HTML (use carefully and avoid XSS!)
       this can be used with HTMLElement instead of string */
    @return realHTML;
}}
</div>

Note

Template feature above is supported for model and component, and you can also run function inside mustache template.

Clone this wiki locally