Pages and Database Driven Website Hosting

restdb.io Pages can serve any content type (HTML, JSON, CSS, RSS, text etc) through an URL endpoint directly from your database.

They are perfect to use for:

  • a database driven website (we can host your domain - see section at the end)
  • reports
  • dashboards
  • feeds
  • pre-made database views (for example in JSON or XML)

You code the view templates using server-side HandlebarsJS tags together with your content type. Pages can also act as components in other Pages by including one in another (see the #include tag below).

Demo site: restdb.site

For a good example of a site created entirely with Pages, visit http://restdb.site. You can view (and steal) the source code to see how things are done.

restdb-site

Creating Pages with HandlebarsJS

The output from a Handlebars template is injected in the HTML (or other content type) on the server before it is sent to the browser. Pages rendered with server templates are fast and demands very few resources from your browser.

General HandlebarsJS tags you can use with Pages can be found here.

restdb.io specific Handlebars-tags and helpers are:

HelperDescription
contextRun database queries and bind data to the Page view context
includeReuse another Page as a fragment
inheritInherit from a master page layout
blockPlace output in master page layout block
ifCondLogic statement
tojsonOutput encoded JSON
rawjsonOutput unencoded JSON
momentDate functions from the moment.js library
authPassword protect pages
trimStringSubstring
fixedNumberNumber decimal format
_String functions from lodash.com library
markdownRender text as Markdown
sortBySort an array in ascending order
sortByDescSort an array in decending order
parseIntParse string to an Integer
switchSwitch case statement

The various helpers are explained below.

context

The #context helper tag defines the data you can display on a Page. It could be a plain JSON object (great for testing), but the main use case is to run one or several database queries and make the result available through Handlebars tags.

In the HTML example below, we fetch data from one collection (contacts), using a query that will give us contacts of category 'customer'.

The query and hints part of the definition are the same we use for the REST API queries. Note that query is required, hints is optional. See the "Querying with the API" docs for details.

    {{#context}}
    {
      "mycust": {
          "collection": "contacts",
          "query": {"category": "customer"},
          "hints": {"$orderby": {"name": 1}}}
      }
    }
    {{/context}}

    <html>
        <body>
            <h1>My customer contacts</h1>
            <ul>
                {{#each mycust}}
                <li>
                    {{name}} {{phone}}
                </li>
                {{/each}}            
            </ul>
        </body>
    </html>

JSON data view example

Creating a data view of the same data in JSON is simple. You just change the content type of the Page to application/json (in the settings menu of the Page) and write the content in the appropriate format (JSON).

    {{#context}}
    {
      "mycust": {
          "collection": "contacts",
          "query": {"category": "customer", "_createdby":"{{user}}"},
          "hints": {"$orderby": {"name": 1}}}
      }
    }
    {{/context}}
    [
      {{#each mycust}}
      {
        "name":"{{name}}",
        "phone":"{{phone}}"
      }
      {{#unless @last}}
      ,
      {{/unless}}
      {{/each}}
    ]

Tip: use {{{tojson mycust}}} to inspect the JSON data or {{{rawjson mycust}}} to output the unescaped JSON data into the page html (note the three brackets) .

include

To include one Page in another we just use the include tag with the name of the Page we wish to include. This makes it easy to reuse HTML partials across many pages.

    <h1>My page title</h1>
    {{include "page-name"}}
    <p>Some text ... 

You can also include content from static files with the static parameter:

    {{include "/folder/file.html" static=true}}

inherit page layouts with #block

The #inherit tag lets you reuse a complete page layout by replacing only #block inside the "master template". First, create a "master page", name it what you like, e.g. masterpage.

    <!-- The masterpage -->
    <html>
        <body>
            <h2>{{{title}}}</h2>
            <p>{{{content}}}</p>
        </body>
    </html>

Next, create a "content page" that will reuse the "master page" layout, name it what you like, e.g. contentpage.

    <!-- The content page -->
    {{#inherit "masterpage"}}
        {{#block "title"}}
        The page title
        {{/block}}

        {{#block "content"}}
        The page content here.
        <hr>
        Something else here.
        {{/block}}

    {{/inherit}}

The output from this page will now be merged into the "master template" to produce the following output.

    <!-- The output html -->
    <html>
        <body>
            <h2>The page title</h2>
            <p>The page content here.
        <hr>
        Something else here.
    </p>
        </body>
    </html>

markdown

This tag will render the content as HTML. The text content must be written in markdown syntax.

{{#each article}}
  {{markdown content}}
{{/each}}  

ifCond

Use this tag to do logical comparisons. The following operators are supported:

OperatorDescription
"=="Equals
"==="Equals
"!=="Not equal
"<"Less than
"<="Less than or equal
">"Greater than
">="Greater then or equal
"&&"And
"||"Or
"%"Modulus
"~"Regular expression match

Example statement using the Equals operator:

{{#ifCond value "===" value2}}
    Values are equal!
{{else}}
    Values are different!
{{/ifCond}}

_ (lodash)

Call a utility function from the Lodash library.

For example rounding a number:

{{_ 'round' customer.salary 2}}

tojson

This tag will output a context variable directly to JSON.

{{{tojson projects}}}

rawjson

This tag will output a context variable unescaped directly to JSON.

{{{rawjson projects}}}

moment - helper for dates

Note that this helper does not use the hash symbol (#) and does not need an end tag. The variable (here: datereceived) must be a valid date.

{{#each application}}
  <p>{{subject}} - {{moment datereceived format="DD/MM/YYYY"}}</p>
{{/each}}</pre>

More examples of MomentJS Handlebars formatting can be found here. You can also check out the MomentJS site.

auth

This tag instructs the server to require an authenticated user.

The example below shows hot to protect a page with a simple username and password.

{{#auth}}
{"password": "secret", "user": "jane"}
{{/auth}}
...

A more elaborate example using a database Collection to authenticate users against.

{{#context}}
{
    "user": {
        "collection": "myusers",
        "query": {"username": "{{credentials.name}}", "password": "{{credentials.pass}}"}
    }
 }
{{/context}}

{{#auth}}
{
    "password": "{{user.0.password}}", "user": "{{user.0.username}}"
}
{{/auth}}
...

trimString

Output a substring from another.

{{trimString str 0 50 '..'}}

fixedNumber

Fixed number of decimals for an integer or float.

{{fixedNumber anumber 2}}

// e.g. 5 => 5.00

sortBy

Sort an array in ascending order. Consider this example where a customer collection has a productlist as an embedded array.

{{#context}}
{
    "customers": {
        "collection": "customers",
        "query": {},
        "hints": {"$orderby": {"Name": 1}}
    }
 }
{{/context}}

<html>
    <body>
        {{#each customers}}
            <p>
            {{this.Name}}
            {{#sortBy this.productlist "Price"}}
                {{#each .}}
                    <div style="margin-left: 20px;">
                        ${{Price}}, {{this.[Product Title]}}
                    </div>
                {{/each}}
            {{/sortBy}}
            </p>
        {{/each}}
    </body>
</html>

Example output:

Bogisich Inc
    $500, Apple II plus
    $560, Apple II
    $700, Apple Lisa
Brakus LLC
    $450, Apple IIe
    $500, Apple II plus
    $700, Apple Lisa
    $999, Apple I
    $1150, Mackintosh SE 30

sortByDesc

Sort an array in descending order. See example above and replace sortBy with sortByDesc

parseInt

Parse a string to an Integer. Second parameter outputs as default value if first parameter is not a valid string.

{{parseInt astring -1}}

switch / case

Switch case statement. Multiple and nested expressions supported.

{{#each orders}}
        <br/>
        Order is shipped to
        {{#switch ShipCity}}

                {{#case 'Reims'}}
                        Home in <strong>{{ShipCity}}</strong>.
                {{/case}}

                {{#case 'Graz' 'rue du Commerce'}}
                        Perfumes region in {{ShipCity}}.
                {{/case}}

                {{#default}}
                        Somewhere else.
                {{/default}}

        {{/switch}}
{{/each}}

Predefined variables

Predefined variables you can use in restdb.io Pages are:

  • {{root}}
    • When you refer other pages, this will always be the correct root. For example if you reference a CSS file named styles.css, you should use it like this <link href="{{root}}/mycss" rel="stylesheet">
  • {{user}}
    • the email of the logged in user (on private pages)
  • {{params}}
    • the query string from the browser as a map, ie.{{params.title}} references ...?title="the title"
  • {{pathparams}}
    • contains path parameters. Note that this requires your page to have the whole path as Page name. For example, a page named "/contacts/:name" can retrieve the path parameter :name using {{pathparams.name}}. Accessing the page with /contacts/john will put "john" into pathparams.name. Note that the page name MUST start with a slash '/' in order for this to work.
  • {{credentials}}
    • For password protected pages it contains name and pass for an authenticated user on a Page using the #auth tag.
    • For pages using Auth0 integration it contains the decoded jwt object.
  • {{db}}
    • The database name for the current instance
  • {{settings}}
    • Global settings properties set for this database

Creating hashmaps for site-wide settings

Sometimes it can be nice to use a restdb.io Collection to store sitewide settings. In this case it is awkward and unreadable to access these data from an array: {{settings.12.name}}. Instead you can map the result of a query to a hashmap as follows:

    {{#context}}
    {
      "settings": {
          "collection": "settings",
          "query": {},
           "as":{
                "type":"map",
                "key":"name"
            }
      }
    }
    {{/context}}

You can now access the settings like this: {{settings.title}}.

Note that the key field (here: name) should be set to be unique.

Cache Page content

In the Settings tab (while in development mode) you can enter a JSON configuration for how the server and clients should cache your Page content.

For example, to cache all Javascript and CSS on the client, and cache a specific Page on both client and server:

{
…
  "restdb": {
    "cache": [
      {
        "content-type": "text/css",
        "client-max-age": 3000
      },
      {
        "content-type": "text/javascript",
        "client-max-age": 3000
      },
      {
        "match": "index\.html",
        "server-max-age": 60,
        "client-max-age": 3600
      }
    ]
  }
    …
}
  • "content-type" - exact match of Page content type
  • "match" - a regular expression that matches your Page name
  • "client-max-age" - client cache in seconds
  • "server-max-age" - server cache in seconds

Hosting a web site using Pages and restdb.io

A restdb.io database with Pages can be used to host a site. To do this, you need to create at least one Page and make it public. Now, go to the "Users and Settings" for your database. There you'll find the "Webhosting" tab and the instructions for hosting your Pages. The "Page name" sets up the default landing page.

domains