scalaplayframework-2.0playframework-2.1scala-template

How to render a template from controller within template -- Java, Play 2.1


Is it possible to call a controller method to render a template within a template? Or is that totally the wrong aproach?

In the div container there is only a sting displayed but not the redered html from my productTable template.

The displayed string inside the <div class="products">:

SimpleResult(200, Map(Content-Type -> text/html; charset=utf-8))

Template:

@categories.map {cat =>
<div>some html</div>
<div class="products">@controller.Products.getByCatergoyId(cat.id)</div>
}

Controller:

public static Result getByCatergoyId(Long catId) {
List<Product> products = Product.find.where().eq("category.id", catId).findList();
return ok(views.html.display.productTable.render(products));
}

Solution

  • If you want to get the code from the productTable view your method shouldn't return a Result but just a String containing rendered code.... aaaannnyyyyway , there is definitely much better way for rendering sub-templates in Play, check the Tags section of the documentation it does exactly what you want directly from the view, of course you will need to pass a product object to it.

    Just create tags package in your view package and add there your sub-template (responsible for rendering only pat of page) it behaves exactly the same as common template.