I have a play-template with javascript code in it. Everything works but it has two disadvantages:
- Bad readability with eclipse-play-plugin, javascript is not colored in code highlighting
- I can't use the jquery-document-ready functionality because (I think) the jquery stuff is not yet loaded at this point of the dom tree. So I had to take the native implementation with
setInterval()
On the other hand, the advantage I have with his solution is:
- I can use the play-scala-template stuff to generate javascript code
- all the code is together in one file and not somehow lost in the
public/javascript
folder
Any suggestion to improve the code is welcome! Thanks
@(categories: List[WikiCategory])
@import play.i18n._
@import helper._
@main(Messages.get("frontend.wiki.title")) {
<form class="form-search">
<input type="text" class="input-medium search-query" placeholder="@Messages.get("frontend.wiki.search.placeholder")" id="searchInput"></input>
<button type="button" class="btn btn-primary" id="searchButton" onclick="search()">@Messages.get("frontend.wiki.search")</button>
</form>
@* most read articles *@
<div class="row">
@components.wikitable(Messages.get("frontend.wiki.mostread"), WikiArticle.findAllMostReadArticles(5), 999)
</div>
@* articles by category *@
@for((category, i) <- categories.zipWithIndex) {
@if(i%2 == 0) { <div class="row"> }
<div class="span6">
@components.wikitable(category.name, WikiArticle.findAllByCategory(category, 5), category.id)
</div>
@if(i%2 == 1) { </div> }
}
<script type="text/javascript">
var search = function() {
var input = $('#searchInput').val();
$.post( "/wiki/search/" + escape(input), function( data ) {
console.log("found in table999 " + data.length + " articles for criteria " + input);
$('#table999').empty();
$('#table999').append($(template(data)));
});
@for((category, i) <- categories.zipWithIndex) {
$.post( "/wiki/search/@category.id/" + escape(input), function( data ) {
console.log("found in table@category.id " + data.length + " articles for criteria " + input);
$('#table@category.id').empty();
$('#table@category.id').append($(template(data)));
});
}
}
var template = function(articles) {
var table = "";
for (var i = 0, limit = articles.length; i < limit; i++) {
table += article(articles[i]);
}
return table;
}
var shortArticleText = function(text) {
var lengthText = 80
if (text.length > lengthText)
return text.substring(0, lengthText) + "..."
else
return text
}
var article = function(article) {
var row = "<tr><td><a href=\"/wikiarticle/" + article.id + "\" class=\"btn btn-primary\">" + article.title + "</a> </td>";
row += "<td>" + shortArticleText(article.text) + "</td></tr>";
return row;
}
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
search();
clearInterval(readyStateCheckInterval);
}
}, 10);
</script>
}