Mantra how-to guide

Define and render a simple view

To define a new view and render it is easy and can be done in minutos. This how-to explains the basics.

08-Mar-2022
A  A  A 

Mantra views are versatile and flexible.

On of the main goals of Mantra is the developer can write common coding tasks easily and with minimal code, with good organization and high reusalibity.

In any Mantra site application, a number of views are defined to include the functionality for the final user.

Mantra expects you to define a hook view, but as we know, the recommended method to define a view is implicity within the file "view.[component name].js", that should be located at "/controllers" folder of the component.

Say a component named "shopitems" and a simple view that shows a basic HTML content with some shopping recommendations, to be shown when the user enters at "/shopitems/showrecommendations".

Any Mantra view route is composed by two elements wit this format: /[component name]/[command name].

To implement the above view, we just need to define two files.

First, the view handler:

"use strict";

module.exports = {
   showrecommendations: async (req,res) => {
      const Mantra = res.MantraAPI;

      // Do some stuff before rendering, like add vars to view, get data items, etc.

      Mantra.RenderView("shopitems.showrecommendations");
   }
}

And, secondly, the showrecommendations HTML file that should be located at "/ui/views/showrecommendations.html", with some HTML code:

<h1>Some recommendations here...</h1>

In two simple files and steps, the route /shopitems/showrecommendations will render that HTML view to the content of the site.

This is the rendering view basics, enough for this how-to, but you need to consider:

  • Usually, the view handler has the logic to retrieve data, process it and render it accordingly.

  • This view, as defined in this simple example, can be open by any user. To include any kind of restrictions, and access condition should be used.

  • RenderView method expect to receive the view to render with the format "[component name].[name of the view]", as explained in [Mantra API reference](https://www.mantrajs.com/docs/33-mantra-API-reference.md.

More about views at Mantra views section.