Mantra how-to guide

Render a simple view

The rendering process of a view is straightfoward with Mantra

29-Mar-2022
A  A  A 

Components can define views to render specific sections of a web site.

You define your views handlers in a file named "view.[component name].js" inside the /controllers folder of the component.

That file is a standard Node.js module which exports a number of properties. These properties, are used as routes in the site.

As an example, give a component named "samplecomponent", we want to define a simple view named "showbasicinfo".

To do that, just create the file /controllers/view.samplecomponent.js, with this content:

module.exports = {
   showbasicinfo: async (req,res) => {
      // Process rendering of the view
   }
}

With this, when running the application, all requests to http://yoursite:port/samplecomponent/showbasicinfo, will be handled by the method defined above.

Now, let's write the code to render a real but simple view. Given there exists a HTML view named "showbasicinfo" as well (located at /ui/views/showbasicinfo.html", with this template expecting a simple Mustache value named "message":

<h1>Simple view</h1>
{{{message}}}

Your view handler can be changed to this:

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

      Mantra.AddRenderValue( "message", "Mantra rocks!");
      Mantra.RenderView( "samplecomponent.showbasicinfo" );
   }
}

And that's all.

Some explanations about this simple code:

  • Only one Mantra API object is created in each request. Because this object is heavy to load and create, for performance reasons, Mantra expects that the same instance will be used by all handlers involved within the same request.

  • With AddRenderValue(), we are adding a value to "message" variable that it is indicated in the view.

  • With RenderView(), we are telling to Mantra to render the expected view "showbasicinfo.html" (that should be located at /ui/views/) of the component "samplecomponent".

This is a simple code snippet to render a view, but the rendering process can be much more complicated according to the functionality of the view.

More about views at official Mantra documentation.

For last, a simple improve of the above code because all rendering methods of Mantra API object can be chained to simplify the client code:

module.exports = {
   showbasicinfo: async (req,res) => {
      res.MantraAPI 
             .AddRenderValue( "message", "Mantra rocks!")
             .RenderView( "samplecomponent.showbasicinfo" );
   }
}