How can I serve mostly static pages from a scala Play! application like an "About" page in different languages? - scala

I am building an application using the Play! framework version 2.0.4. Some pages that are legally required such as an imprint mostly contain lots (some 10k each) of static text which I would like to provide in different languages.
In versions 1.x there was an #include directive that allowed to construct the actual resource path using the current Lang.
What is the recommended way of implementing sth similar with Play 2.x?
Thank you & best regards,
Erich

I'm not 100% certain how you implement it as of now, but here's what I've come up with.
You could just write your own include helper. Save the following in a file Helpers.scala in your views folder. Explanations are in the code's comments.
package views.html.helper
object include {
import play.api.templates.Html
import play.api.Play
import play.api.Play.current
import play.api.i18n._
// The default is to look in the public dir, but you can change it if necessary
def apply(filePath: String, rootDir: String = "public")(implicit lang: Lang): Html = {
// Split filePath at name and suffix to insert the language in between them
val (fileName, suffix) = filePath.splitAt(filePath.lastIndexOf("."))
// Retrieve the file with the current language, or as a fallback, without any suffix
val maybeFile =
Play.getExistingFile(rootDir + "/" + fileName + "_" + lang.language + suffix).
orElse(Play.getExistingFile(rootDir + "/" + filePath))
// Read the file's content and wrap it in HTML or return an error message
maybeFile map { file =>
val content = scala.io.Source.fromFile(file).mkString
Html(content)
} getOrElse Html("File Not Found")
}
}
Now in your imprint.scala.html you could call it like this:
#()(implicit lang: Lang)
#import helper._
#include("static/imprint.html")

Way showed by Schleichardt was used in play-authenticate to select mail templates in different languages and now it's changed to work with reflections on the controller, so maybe it can be interesting for you. Anyway it was intendent to keep standard templating possibilities (cause each mail need to be personalized before send)
For static info pages, you can just save the code for each language with suffix ie. impressum_en.html, impressum_de.html in the file system and use simple controller which will find file with proper suffix and return its content exactly as it is... all you need probably to return Ok(fileContent) and set the Content-Type manually to text/html.
Other option is doing the similar thing but storing it in the DB, so you can create simple back-end and edit it with browser.
If you still need to replace some elements, you can do it with some ###MARKER### in the code + simple String operations, or with JavaScript on the client side.

Templates in 2.0 work a bit differently. The Scala based templates are compiled. From one template instead of 'including' another, you can make a call to it. I'm not sure exactly what you mean by the language thing. In 2.0 though, a parameter to the template could be the language.
Example template named 'included' in package whateverpackage.
#(lang: Lang)
...
Example calling a template named 'included':
#import whateverpackage._
#included(Lang("en"))

#()(implicit lang: Lang)
#main(Messages("imprint")) {
#lang match {
case Lang("de", _) => { #germanImprint() #* uses app/views/germanImprint.scala.html file *#}
case _ => { #englishImprint() }
}
}

Related

Do Flask/Jinja2 have a provision to save rendered templates during debugging?

While debugging it's useful to view the rendered HTML and JS templates through a "view source" menu item in a browser, but doing so forces one to use the UI of the browser.
Does Jinja2 (or Flask) provide a facility to save the last n rendered templates on the server? It would then be possible to use one's favorite editor to view the rendered files, along with using one's familiar font-locking and search facilities.
It's of course possible to implement such a facility by hand, but doing so smacks too much like peppering one's programs while debugging with print statements, an approach that doesn't scale. I'm seeking a better alternative.
I'd think the easiest thing to do would be to use the after_request hook.
from flask import g
#main.route('/')
def index():
models = Model.query.all()
g.template = 'index'
return render_template('index.html', models=models)
#main.after_request
def store_template(response):
if hasattr(g, 'template'):
with open('debug/{0}-{1}'.format(datetime.now(), g.template), 'w') as f:
f.write(response.data)
return response
Here are the docs.
http://flask.pocoo.org/snippets/53/
As far as only collecting the last n templates I'd likely setup a cron job to do that. Here is an example
import os
from datetime import datetime
def make_files(n):
text = '''
<html>
</html>
'''
for a in range(n):
with open('debug/index-{0}.html'.format(datetime.now()), 'w') as f:
f.write(text)
def get_files(dir):
return [file for file in os.listdir(dir) if file.endswith('.html')]
def delete_files(dir, files, amount_kept):
rev = files[::-1]
for file in rev[amount_kept:]:
loc = dir + '/' + file
os.remove(loc)
if __name__ == '__main__':
make_files(7)
files = get_files('debug')
print files
delete_files('debug', files, 5)
files = get_files('debug')
print files
EDIT
reversed order of files inside the delete function so it will keep the most recent files. Also unable to find a way of accessing the original template name to avoid hardcoding.
EDIT 2
Alright so updated it to show how you can use flask.g to pass the template name to the after_request function
docs http://flask.pocoo.org/docs/0.11/testing/#faking-resources

Downloadable xml files in Play Framework

I am a Scala/PlayFramework noob here, so please be easy on me :).
I am trying to create an action (serving a GET request) so that when I enter the url in the browser, the browser should download the file. So far I have this:
def sepaCreditXml() = Action {
val data: SepaCreditTransfer = invoiceService.sepaCredit()
val content: HtmlFormat.Appendable = views.html.sepacredittransfer(data)
Ok(content)
}
What it does is basically show the XML in the browser (whereas I actually want it to download the file). Also, I have two problems with it:
I am not sure if using Play's templating "views.html..." is the best idea to create an XML template. Is it good/simple enough or should I use a different solution for this?
I have found Ok.sendFile in the Play's documentation. But it needs a java.io.File. I don't know how to create a File from HtmlFormat.Appendable. I would prefer to create a file in-memory, i.e. no new File("/tmp/temporary.xml").
EDIT: Here SepaCreditTransfer is a case class holding some data. Nothing special.
I think it's quite normal for browsers to visualize XML instead of downloading it. Have you tried to use the application/force-download content type header, like this?
def sepaCreditXml() = Action {
val data: SepaCreditTransfer = invoiceService.sepaCredit()
val content: HtmlFormat.Appendable = views.html.sepacredittransfer(data)
Ok(content).withHeaders("Content-Type" -> "application/force-download")
}

TypeLite generate external modules?

I am trying to generate external modules rather than a type definition file. I believe I need to do the following:
Change the extension of the file to .ts instead of .d.ts.
Generate one file per module.
Add the key word "Export" in front of each interface and enum.
I was easily able to change the extension of the file by changing the "output extension" setting in the tt file.
I cannot figure out how to split the modules into separate files.
I cannot figure out how to add the Export key word to each interface.
TypeLITE doesn't support generating multiple files. This feature has been requested by several users, but I am not aware of a simple way to generate multiple files from the single tt file.
export keyword can't be added without changing source code of the library (TsGenerator.cs). This is very specific requirement, so I probably won't add it to the library.
TypeLite is a good project but lacking in Documentation and examples, it's open source so anyone can contribute and make it better.
As for creating a file per class i solved it using the code below.
private static void GenerateTypeScriptContracts(string assemblyFile, string outputPath)
{
// Clean TS Folder
System.IO.DirectoryInfo di = new DirectoryInfo(outputPath);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
// --
var assembly = Assembly.LoadFrom(assemblyFile);
// If you want a subset of classes from this assembly, filter them here
var models = assembly.GetTypes();
foreach (var model in models)
{
var generator = new TypeScriptFluent()
.WithConvertor<Guid>(c => "string")
.WithMemberFormatter((identifier) => Char.ToLower(identifier.Name[0]) + identifier.Name.Substring(1));
generator.ModelBuilder.Add(model);
// Generate TS interface definitions
var tsClassDefinitions = generator.Generate(TsGeneratorOutput.Properties | TsGeneratorOutput.Fields);
File.WriteAllText(Path.Combine(outputPath, "I" + model.FullName.Replace("ProjectName.DtoModels.", "") + ".ts"), tsClassDefinitions);
}
}

Play Framework Modules: module specific assets

I'm new to play framework and I'm trying to separate my app into multiple, smaller modules. For instance, I want to have a header module and a sidebar module.
For now, I've created these modules and a page module, that will render each module into its right place.
Here's an example of a module code:
package controllers
import play.api.templates._
object SidebarService {
def getHTML() : Html = {
views.html.sidebar(name = "variable", repeat = 5)
}
}
Note that it is returning an Html object.
And here's an example of a page module
package controllers
import play.api._
import play.api.mvc._
object Application extends Controller {
def index = Action {
var sideBar = SidebarService.getHTML()
Ok(views.html.index(sideBar)("Your new application is ready."))
}
}
This works fine, but I'm a little bit confused on how to get module-specific Assets to be included in page module, e.g. sidebar module has specific css and javascript files that will be "included" (and minified) in the <head> tag of page module. First, am I going in the right direction for modularization? Secondly, how could I accomplish module-specific assets?
Any pointers would be great.
Regarding inclusion of module-specific assets, I guess you can always do something like:
package controllers
import play.api.templates._
object SidebarService {
def getAssets : Html = {
// your <link> and <script> tags here
}
def getBody : Html = {
views.html.sidebar(name = "variable", repeat = 5)
}
}
I suppose you're going to make something like PageService a trait with getAssets and getBody as abstract methods. Your approach for modularization seems OK. In order for the page to have an arbitrary number of modules, I guess I would pass as argument to views.html.index not only sideBar, but maybe a Map[String, PageService] containing the various modules identified by a string (or symbol, or any other thing you want) key, e.g. Map("header" -> HeaderService, "sidebar" -> SidebarService). That way, in the view, you can get all the assets for the modules you are using and lookup by the keys you defined to know what to draw in each placeholder.

MVC on Lift/Scala

Has anyone tried to do a scala/lift application using MVC instead of view-first?
I know that you can create Controllers/views as:
package test.test.test.view
...
Lots of imports
...
class MvcRocks extends LiftView {
def dispatch = {
case "rule" => ruleDispatch _
case "bar" => barDispatch _
}
def barDispatch(): Box[NodeSeq] = {
Full(<lift:embed what="/mvc_rucks/bar" />)
}
}
And this code will be accessible if you add it to the menu(in the boot), even if its hidden as:
val entries = Menu(Loc("Home", List("index"), "Home")) ::
List(Menu(Loc("MvcRock", List("mvc_rocks", "bar"), "Mvc really Rocks", Hidden)))
LiftRules.setSiteMap(SiteMap(entries:_*))
Now, of course this will make it so, you declare every action in the menu, then have a case for each action(per controller) and that would open the "view" (that would be a file in /mvc_rucks/bar.html).
My question is, if you would implement a full mvc, you would need to put all your logic in the action barDispatch, but how would you send those variables to the HTML template? and how would you receive post/get information?
(Notice that if you html code has lift bindings, it will of course act as view-first, even after you did MVC before).
Since your question is not specific to Lift, I'd recommend you the Playframework. The version 1.1 supports Scala 2.8.
Playframework is totally MVC with a fantastic template engine and allows you to choose freely between java/scala.
And I say: To use Play, you don't need 'nuclear scientist knowledge'. Try it!