Tuesday, December 21, 2021

Mustache renderings with Sitecore, A JAMstack architecture

Mustache is a logic less rendering framework for HTML/CSS, After the introduction of JSS framework the utility of this framework has been undermined but still it has proven to be beneficial in a few use cases, like:

You want a block stacking approach in a single page application, Example: the rendering is made up of many small html templates and content editor can pick among these,

The solution is dependent upon external APIs/Lambdas for server side processing and you want to tell the API sources to the client at runtime only, so allowing your content editors to setup the APIs/Lambdas in content editor and render these in hidden fields somewhere to client,

A rich text box has a html with the dynamic values, html can change anytime based on business requirements, and dynamic values come from server in JSON format,

Let me demonstrate the implementation of the last example here, and rest of the examples will be intuitive,

1. Create a reference for mustache.min.js in the main layout,

2. Create a view rendering:

<article  data-block-id="{{Id}}" data-scripts-loaded="false" >

<script>

function getDynamicContents() {

            var htmlTemplate= @Model.RTEhtmlTemplate;

                $.ajax({

                    method: 'POST',

                    url: @Model.TransactionSecret,

                }).done(function (response) {

                    Mustache.render(htmlTemplate, response)

                });

            }

</script>

    {{#Title}}<h2>{{.}}</h2>{{/Title}}

    {{#DynamicContent}}

    <div class="dynamicText">

        {{{Text}}}

    </div>

    {{/DynamicContent}}

<hiddenField id="hdnTC" onLoad=getDynamicContents()>{}</hiddenField>

</article> 

3. The above view has a model which gives the dynamic contents from RTE, something like:

@Model.RTEhtmlTemplate

@Model.TransactionSecret

4. Create an API controller that gives the response in following  JSON format, text value is coming from dynamic server side logic :

DC:{DynamicContent : {Text: Value} }

5. call getDynamicContents() at some event like onLoad above, additional progress bar code while the dynamic values are getting rendered will look good,


with the recent advancements in the client side JS frameworks and libraries, mustache is still a light option for these use cases

No comments: