Controller examples

Several examples of controllers and their usage below

Renders random number

This example has a controller with two modes, index и rnd1000.

code/controllers/Rendom.js
exports.add=[{
    _type:"controller",
    _config:{name:"Random"},
    index:function() {
        return Math.floor(Math.random()*100);
    },
    rnd1000:function() {
        return Math.floor(Math.random()*1000);
    }
}];

Renders available html pages

To do this, a request is made to the database and a fragment of an HTML document is generated. This generation method is NOT RECOMMENDED and is presented for informational purposes only. The option below shows the correct way to create HTML documents.

code/controllers/PagesList.js
exports.add=[{
    _type:"controller",
    _config:{name:"PagesList"},
    index:function() {
        var sqlq="select alias from Tpages";
        var pages=this.site.sql.execute_and_fetch_single(sqlq,{});
        var html="<div class='items'>";
        html+=pages.map(function(p) { return "<div class='item'><a href='"+p.alias+"'>"+p.alias+"</a></div>"; });
        html+="</div>";
        return html;
    },
}];

Renders html page, displaying users in database

This is a correct and recomended practice of making a controller, with all components placed in separate files.

code/controllers/UsersList.js
exports.add=[{
    _type:"controller",
    _config:{name:"UsersList"},
    index: function() {
        this.users=this.site.sql.execute_and_fetch("users/list",{});
        return this.Cview();
    },
    view: function() {
        this.userinfo=this.site.sql.execute_and_fetch_one("users/get",{id:this.fields.id});
        return this.Cview();
    }
}];

code/sql/users/list.sql
select
    u.id,
    u.login
from
    Tusers u
where
    u.enabled=1
order by
    u.login

code/sql/users/get.sql
select
    u.id,
    u.login,
    to_char(u.date_cr,'DD.MM.YYYY') as date_cr
from
    Tusers u
where
    u.id=:id

code/views/controllers/UsersList/index.html
<table class="table">
<thead>
    <tr>
        <th>ID</th>
        <th>Login</th>
    </tr>
</thead>
<tbody>
    {{foreach u in users}}
    <tr>
        <td><a href="{{action}}?mode=view&id={{u.id}}">{{u.id}}</a></td>
        <td>{{u.login}}</td>
    </tr>
    {{/foreach}}
</tbody>
</table>

code/views/controllers/UsersList/view.html
<table class="table">
<tbody>
    <tr><td>ID</td><td>{{u.id}}</td></tr>
    <tr><td>Login</td><td>{{u.login}}</td></tr>
    <tr><td>Creation date</td><td>{{u.date_cr}}</td></tr>
</tbody>
</table>