play framework call helper function from another template - scala

I have a helper file utils.scala.html which looks like below:
#renderTableRow(columnTag: String, columns: Seq[String]) = {
<tr>
#for(column <- columns) {
<#columnTag>
#column
</#columnTag>
}
</tr>
}
I want to call this helper function from rest of my view files to create table headers.
#import views.html.mycommon.utils
#renderQuotesTable() = {
<table class="table table-bordered table-striped">
<thead>
#utils.renderTableRow("th", Seq("Name", "Date of Birth", "Age"))
</thead>
<tbody>
</tbody>
}
But, I get the following the error
value renderTableRow is not a member of object views.html.mycommon.utils.
what am I missing here?

You cannot import the declared functions of another template. Execute sbt doc and in the generated Scala Doc is no clue of renderTableRow in the util object. "renderTableRow" is wrapped into the apply method as you can see in the generated source for the template: "target/scala-2.10/src_managed/main/views/html/mycommon/utils.template.scala".
For every function you want to use in another template you hava to create a template or a function in a real Scala singleton object.

Related

Powershell and Razor Template

I'm using PowerShell and Render-RazorTemplate.ps1 to create a html page
I have a 'System.Collections.Hashtable' passing to my Model and i'm not getting this to work
#foreach (var s in Model)
{
<div class="BTC-setting"><i class='fa #(s["Icon"])'></i><span>#s["Name"]</span></div>
}
If I use like this
class='fa #(s["Icon"])'
I have an error like
The name 'WriteAttribute' doesn't exist on the actual context
>>> WriteAttribute("class", Tuple.Create(" class=\'", 225), Tuple.Create("\'", 248)**
If I remove the #(s["Icon"]) from inside of the property class it works and shows me the value
Someone have any ideas about this?
Just found the solution to my issue, just put #: at the begging of the html tags that uses variables inside quotes
ISSUE
#foreach (var s in Model)
{
<div class="BTC-setting"><i class='fa #(s["Icon"])'></i><span>#s["Name"]</span></div>
}
SOLUTION
#foreach (var s in Model)
{
#:<div class="BTC-setting"><i class='fa #(s["Icon"])'></i><span>#s["Name"]</span></div>
}

The foreach tag in JSP and how to write the code in the Java controller

I have one controller (RegisteredController.java) , and I want that the output of the controller is displayed in the JSP (its name is commment_form.jsp). So I use a forEach tag in the jsp to display a list of comments (the comments which the user has inserted about a given resource). For "resource" I usually mean an image. So there are a list of comments about an "image" and I want that all the comments are all displayed in the bottom page, when a comment is going to be inserted into the comment form. My question is how must be written the code into the controller in order to set the output for the jsp ? Should I use a #ModelAttribute , a put-attribute or something else ? Here is the code of the controller and of the jsp :
The comment_form.jsp is:
<form:form modelAttribute="comments">
<table class="commento">
<tr>
<th/>
<th>ID</th>
<th>Contenuto</th>
</tr>
<c:forEach items = "${comments}" var="comment">
<tr>
<td><c:out value="${comments.content}"></c:out></td>
<td><c:out value="${comments.content}</c:out></td>
</c:forEach>
</table>
</form:form>
The RegisteredController.java is:
#RequestMapping("/comment.do")
public String comment(#ModelAttribute Comment comment, BindingResult
bindingResult, Model model, Locale locale) {
User user=userService.getUserCurrent();
comment.setDatePubblication(SQLUtility.getCurrentDate());
comment.setIdUser(user.getId());
commentService.create(comment);
Object[] args = { comment.getId() };
String message = messageSource.getMessage("message.update", args,locale);
List<Comment> comments =
commentService.findAllCommentByResource(comment.getIdResource());
model.addAttribute("comments", comments);
model.addAttribute("id",comment.getIdResource());
model.addAttribute("message", message);
model.addAttribute("comment", comment);
return "redirect:/registered/comment_start.do";
}
Please any help ? I will appreciate . Thanks you.
In case of redirect pass additional data as redirect attributes.
To carry data across a redirect use RedirectAttributes#addFlashAttribute(key, value).
What Java doc says:
A RedirectAttributes model is empty when the method is called and is never used unless the method returns a redirect view name or a RedirectView.
After the redirect, flash attributes are automatically added to the model of the controller that serves the target URL.
Read more...
One extra note :
In JSP it should be ${comment.content} instead of ${comments.content}

Playframework - querying and displaying results from multi-table join

I'm a newcomer to java and the play framework (I'm using play 1.2.2 with a local MySQL5 database). I'm trying to query a couple of tables in a database and display the table join results on a web page.
This is what I have in the various bits:
Controller :-
public static void index() {
List<Mutation> mutation_list= Mutation.getDisorderGene();
render(mutation_list);
}
Model :-
public class Mutation extends Model {
public static List<Mutation> getDisorderGene() {
EntityManager entityManager = play.db.jpa.JPA.em();
List<Mutation> muts = entityManager.createNativeQuery("select disorder_name, gene_name from Disorder,Mutation where Disorder.id = Mutation.disorder_id order by disorder_name, gene_name").getResultList();
return muts;
}
View :-
#{list items:mutation_list, as:'mutation'}
<tr>
<td>${mutation.disorder_name}</td>
<td>${mutation.gene_name}</td>
</tr>
#{/list}
And this is the error message I get!
Template execution error
Execution error occured in template /app/views/Stu/index.html.
Exception raised was MissingPropertyException : Exception evaluating
property 'disorder_name' for java.util.Arrays$ArrayList, Reason:
groovy.lang.MissingPropertyException: No such property: disorder_name
for class: java.lang.String.
I'm unsure where the problem lies. Is it with the JPA table join query or is something wrong in the view.
Are there any changes in the view I can make to display the columns?
Many thanks.
A native query that selects multiple columns by default returns them as Object[], thus your getDisorderGene() should return a List<Object[]>, and your template should look as follows:
#{list items:mutation_list, as:'mutation'}
<tr>
<td>${mutation[0]}</td>
<td>${mutation[1]}</td>
</tr>
#{/list}
What if you put the as clausule...
select disorder_name as NameMyPropertyModelClass, gene_name as NameMyPropertyModelClass
from Disorder,Mutation
where Disorder.id = Mutation.disorder_id order by disorder_name, gene_name

foreach statement cannot operate on variables of type '' because '' does not contain a public definition for 'GetEnumerator'

I Got an Error Like This
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1579: foreach statement cannot operate on variables of type 'EventListing.Models.EventInfo' because 'EventListing.Models.EventInfo' does not contain a public definition for 'GetEnumerator'
Source Error:
Line 106: </th>
Line 107: </tr>
Line 108: <% foreach (var model in Model)
Line 109: { %>
Line 110: <tr>
Model
public static List<EventInfo> EventList()
{
var list = new List<EventInfo>();
Dbhelper DbHelper = new Dbhelper();
DbCommand cmd = DbHelper.GetSqlStringCommond("SELECT * FROM WS_EVENTINFO");
DbDataReader Datareader = DbHelper.ExecuteReader(cmd);
while (Datareader.Read())
{
EventInfo eventinfo = new EventInfo()
{
EVENT_ID = Convert.ToInt32(Datareader[
View Page
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<EventListing.Models.EventInfo>" %>
<% foreach (var model in Model)
{ %>
<tr>
<td>
<%= Html.ActionLink(Model.TITLE,"Detail", new {id = Model.EVENT_ID})%>
How can solve this Issue, i'm Using MVC2 Framework.
You need to bind a collection as a model. Check this post for details: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
View
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IList<EventListing.Models.EventInfo>>" %>
Controller
public ActionResult List()
{
return this.View(EventList());
}
Or use some another type for model and define property List<EventInfo> Events in it. Then iterate in following way:
<% foreach (var model in Model.Events)
{ %>
Also, Visual Studio can do it for you:
Presumably what you are trying to do is:
foreach(var model in Model.EventList()) {..}
Although it is difficult to be sure.
If you require the syntax you used then Model will have to be an object of a class with a GetEnumerator() method.

Output a list to a template in lift

How can I output a list of things in a template in Lift?
Let say for example that I have List[User] and I want to output it as a table. In Django, I would use a context variable "users" and iterate through it in the template like so:
//controller
user = User.objects.all()
context = {'users' : users}
return render_to_template('results.html', context}
//view
<table>
{% for user in users %}
<tr><td>{{user.name}}</td>
<td>{{user.email}}</td>
</tr>
{% endfor %}
</table>
I appreciate any help.
PS: Could you also show me an example of the scala side - as I am clueless about how to approach this problem.
Template
<ul>
<lift:UserSnippet.showAll>
<li><foo:userName />: <foo:age /></li>
</lift:UserSnippet.showAll>
</ul>
Snippet Class
I'm assuming users is a List[User].
import scala.xml.NodeSeq
import net.liftweb.util.Helpers
class UserSnippet {
def showAll(in: NodeSeq): NodeSeq = {
users.flatMap { user => Helpers.bind("foo", in, "userName" -> user.name, "age" -> user.age) }
}
}
See the lift wiki articles on designer friendly templates and snippets for more information.
if you're looking to use a pure java list, say an ArrayList from a seperate java call...you can do it this way....
Make sure to import the java conversions, and your java class file where your list is being created
(i'm assuming we have a list of "people" objects that is being returned from your java file, which would include a name, age, and sex properties)
//SCALA Code
import scala.collection.JavaConversions._
import my.java.package.something._
import scala.xml.NodeSeq
import net.liftweb.util.Helpers
class mySnippet {
//You want to run the ".toList" on your java list, this will convert it into a scala list
val myScalaList = my.java.package.something.buildMyList().toList
//This is the function that will bind the list to the html view
def displayPeople(html : NodeSeq) : NodeSeq = {
myScalaList.flatMap{person => bind("info", html,
"name", person.name,
"age", person.age,
"sex", person.sex)}
}
}
//HTML code
<table>
<tr>
<td>Name</td>
<td>Age</td>
<td>Sex</td>
</tr>
<lift:mySnippet.displayPeople>
<tr>
<td><info:name></info:name></td>
<td><info:age></info:age></td>
<td><info:sex></info:sex></td>
</tr>
</lift:mySnippet.displayPeople>
</table>
Hope this helps :)
-kevin