Tag: Sitecore

Use Handlebar template to bind JSON from Sitecore MVC Controller

In Sitecore MVC as we all know how to bind data synchronously by using inbuilt View and controller rendering but now  we will see in this article how we can bind the Sitecore Item data as json to view using handlebar template framework in asynchronous call.

Following are the steps we have to follow:

  1. Add handlebar framework reference to your layout. Handlebar file is hosted on cdn also it is up to you to direct reference from cdn or download and add to your solution

https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.10/handlebars.amd.js

  1. Create MVC controller inheriting the MVC/Sitecore MVc base controller.
  2. Add action named as example GetArticle() to controller class and return type would ben JSON result set by using Json() method
  3. Create one repository class which bind the model.
  4. Register route for controller override the Sitecore MVC pipeline.
  5. Implement AJAX call and bind with the handlebar template

Controller Class:

public class ArticleController : Controller

{

private readonly IArticleRepository _articleRepository;

public ArticleController () : this(new ArticlerRepository ())

{

}

public AccountsController(IArticleRepository articleRepository)

{

this. _articleRepository = articleRepository;

}

 

[HttpGet]

public JsonResult GetArticle ()

{

List<Article> lstArticle=     this. _articleRepository.GetArticle();

return Json(lstArticle, JsonRequestBehavior.AllowGet);

}

}

Model Class:

public class Article

{

public  string Url { get; set; }

public string Title { get; set; }

public string ShortDescription { get; set; }

}

Repository class interface: Create interface for repository class

interface IArticleRepository

{

string List<Article> GetArticle();

}

Repository class:

public class ArticlerRepository : IArticleRepository    {

/// <summary>

/// Get article sitecore

/// </summary>

/// <returns></returns>

 

public List<Article> GetArticle()
{

List<Article> lstArticle = new List<Article>();
Item aticleRootItem = Mvc.Presentation.RenderingContext.Current.Rendering.Item;

if (aticleRootItem != null && aticleRootItem.HasChildren)
{
foreach (Item childrenItem in aticleRootItem.Children)
{
Article objArticle = new Article();
if (childrenItem.IsDerived(Templates.Article.ID))
{

objArticle.Url = childrenItem.Fields[“Url”]!=null?childrenItem.Fields[“Url”].Value : string.Empty;
objArticle.Title= childrenItem.Fields[“Title”] != null ? childrenItem.Fields[“Title”].Value : string.Empty;
objArticle.ShortDescription = childrenItem.Fields[“ShortDescription”] != null ? childrenItem.Fields[“ShortDescription”].Value : string.Empty;

lstArticle.Add(objArticle);
}
}
}

return lstArticle;
}

}

 

Register route for controller override the Sitecore MVC pipeline

<pipelines>
<initialize>
<processor type=”RegisterWebApiRoutes, dll name”
patch:before=”processor[@type=’Sitecore.Mvc.Pipelines.Loader.InitializeRoutes, Sitecore.Mvc’]” />
</initialize>
</pipelines>

using Sitecore.Pipelines;
using System.Web.Mvc;
using System.Web.Routing;
/// <summary>
/// Register Routes for controller
/// </summary>
public class RegisterWebApiRoutes
{
public void Process(PipelineArgs args)
{
RouteTable.Routes.MapRoute(“Api”, “api/Article/{action}”, new
{
controller = “Article”
});
}
}

Bind article Data on UI using Handlebar framework: Create one Sitecore MVC rendering view named “Articlelst.cshtml”and this handlebar template for article list.

//Handle bar template will rendered articles on page load

*************************************************************************************

Handle Bar template definition for Article list

*************************************************************************************

“<” script id=”application-declined-template” type=”text/x-handlebars-template” “>”

{{#each lstArticle }}

{{{Title}}}

{{{Title}}}

{{{ShortDescription}}}

{{/each}}

“<” / script “>”

Add this JavaScript function to View on document ready function:

$(document).ready(function () {

function GetArticle() {

var url = ‘api/Article/GetArticle’;

$.ajax({

type: get,

contentType: ‘application/json; charset=UTF-8’,

url: url,

cache: false,

success: function (data, status) {

var articleData = JSON.parse($.trim(data.lstArticle));

var source = $(“#article-template”).html();

var template = Handlebars.compile(source);

$(‘.Article-content’).empty();

$(‘.Article-content’).append(template(articleData));

},

error: function (status) {

console.log(“error”, data);

}

});

}

});

 

 

Handlebar reference urls:

https://www.sitepoint.com/a-beginners-guide-to-handlebars/

http://javascriptissexy.com/handlebars-js-tutorial-learn-everything-about-handlebars-js-javascript-templating/

http://handlebarsjs.com/