scala - Play Framework / Twirl Dynamically include templates -
use case: have route handling requests @ host:port/p route looks following:
get /p/*path controllers.application.p(path: string)
the p
method gets data , passes right through view p
:
return ok(p.render(currentsession));
in view want import template if there exists 1 matches string in passed data. in case string represents model object name such "user" , if there matching template views/custompages/user.scala.html
. if there no matching template, use generic 1 such views/generic.scala.html
.
i have 2 parts question:
part 1: see can check template existence doing following:
@if(custompages.user != null) { <p>it exists!</p> }
but if change custompages.usera
(a non existent template) compilation error (object usera not member of package
). how can check?
part 2: how can check using string have representing model class? concatenating in place of hard coded "user" in answer part 1?
am going wrong way? doing supposed handled in controller using reflection matching template render appropriate one?
i decided work problem controller instead of view. code used in case else ends here looking similar answer.
notes: associatedentity how determining template render invoking class render , passing own session object parameter used following create answer: play framework 2.1.3 function render scala template given parameters
thank @biesior suggestion!
public result p(string uri) { session currentsession = getsession(); final class<?> clazz; try { clazz = class.forname("com.domain.views.html." + currentsession.currentpage.associatedentity.getsimplename()); //assumed have string parameter template java.lang.reflect.method render = null; try { render = clazz.getdeclaredmethod("render", session.class); } catch (nosuchmethodexception e) { e.printstacktrace(); } play.twirl.api.html html = null; try { html = (play.twirl.api.html) render.invoke(null, currentsession); } catch (illegalaccessexception e) { e.printstacktrace(); } catch (invocationtargetexception e) { e.printstacktrace(); } return ok(html); } catch (classnotfoundexception e) { return ok(p.render(currentsession)); } }
Comments
Post a Comment