Mantra how-to guide

How to add a custom Mantra "extend"

Extend components assets with Mantra "extends": a way for the components to define new types of "hooks"

07-Mar-2022
A  A  A 

Mantra defines a number of default assets, like views, blocks, prerequests, posts, middlewares, etc., as you can read at Component Assets in official documentation.

However, any component can expose new kinds of assets so that any other components can consume them.

We can do this using the "hook" type of name "Extend".

This hook only requires the property "Type" so you can define a type of hook with any number of other properties you need.

For instance, let's say we want to declare a new extend to define menu entries; we can do that defining an extend of type "mysitemenu" (or any other string):

MantraAPI.Hooks("mycomponent)
    .Extend([{
        Type: "mysitemenu",
        Weight: -20,
        Title: "Log user",
        View: "user.loguser"
    }]);

This "extend hook" of type "mysitemenu" comes with a number of properties (Weight, Title and View, or any other you could need).

Any component can define hook of type "mysitemenu", so, the component who makes something useful with them, can ask Mantra to get all hooks registrations of that type, with:

const allMySiteMenuItems = Mantra.GetExtendsByType( "mysitemenu" );

This method from Mantra API, will return all hooks of type "mysitemenu" registered by all components active in the current application.

Mantra extends is a mecanism to create new kind of assets in adition to Mantra default ones.

Here there's another example extracted from a real project:

 Mantra.Hooks("forms")
    .Extend([{
        Type: "formvalidator",
        Name: "email",
        Handler: FormsValidatorHandlers.IsEmail
    }, {
        Type: "formvalidator",
        Name: "notempty",
        Handler: FormsValidatorHandlers.NotEmpty
    }, {
        Type: "formvalidator",
        Name: "string64",
        Handler: FormsValidatorHandlers.String64
    }]);

"Extends" is one of the abilities of Mantra to add new kind of assets transparently to other components.