This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Scala and templates?

42 replies
Detering Dirk
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.

Hello all,

I would like to hear some opinions/ideas/comments
regarding templates in Scala.

Every now and then I face the need to create
textual output, often it is to generate some kind
of code or report.

One question that arises then is, which template
engine works seamlessly enough with Scala to
become the tool of choice?

How does Scala integrate with Velocity, FreeMarker,
what else?

But often the script is so short, it would be oversize
to use an additional external template system.

Well, Groovy has GStrings, but much more the
TemplateEngine hierarchy, where the SimpleTemplateEngine
most often is sufficient for my tasks.

So Groovy has a good backend for text generation, while
I do the parsing task often by hand with pattern matching
and switch statements. (KISS principle)

Scala OTOH has a very interesting frontend with the
parser combinators, allowing to specify parsers as grammars.

But what about the backend? As long as one generates
XML (HTML) output, there is a tight integration.

The second question is: What about a likewise integrated
textual construction system?

What I could imagine would be some kind of internal DSL
or compiler plugin, allowing to construct methods with
a signature like
def someTemplate( ):String = {
.... // template code
}

But the template code would look more like PHP or JSP or the like,
making the text the main code but with the possibility to escape
back to scala, to define looping and conditionals.

Would that be doable? Are there perhaps yet any ideas or even
activities in a comparable direction?

I am eager to hear your opinions about that topic.

KR
Det

dcsobral
Joined: 2009-04-23,
User offline. Last seen 38 weeks 5 days ago.
Re: Scala and templates?
It would ne bice, but have you considering just apply ".text" to the xml? You might achieve your goals that way.

On Wed, Dec 2, 2009 at 1:23 PM, Detering Dirk <Dirk.Detering@bitmarck.de> wrote:
Hello all,

I would like to hear some opinions/ideas/comments
regarding templates in Scala.

Every now and then I face the need to create
textual output, often it is to generate some kind
of code or report.

One question that arises then is, which template
engine works seamlessly enough with Scala to
become the tool of choice?

How does Scala integrate with Velocity, FreeMarker,
what else?


But often the script is so short, it would be oversize
to use an additional external template system.

Well, Groovy has GStrings, but much more the
TemplateEngine hierarchy, where the SimpleTemplateEngine
most often is sufficient for my tasks.

So Groovy has a good backend for text generation, while
I do the parsing task often by hand with pattern matching
and switch statements. (KISS principle)

Scala OTOH has a very interesting frontend with the
parser combinators, allowing to specify parsers as grammars.

But what about the backend?  As long as one generates
XML (HTML) output, there is a tight integration.

The second question is: What about a likewise integrated
textual construction system?

What I could imagine would be some kind of internal DSL
or compiler plugin, allowing to construct methods with
a signature like
   def  someTemplate( <some params> ):String = {
        .... // template code
   }

But the template code would look more like PHP or JSP or the like,
making the text the main code but with the possibility to escape
back to scala, to define looping and conditionals.

Would that be doable? Are there perhaps yet any ideas or even
activities in a comparable direction?

I am eager to hear your opinions about that topic.

KR
Det


--
***********************************************************************

Die Information in dieser E-Mail ist vertraulich und ist ausschliesslich
fuer den/die benannten Adressaten bestimmt. Ein Zugriff auf diese
E-Mail durch andere Personen als den/die benannten Adressaten ist
nicht gestattet. Sollten Sie nicht der benannte Adressat sein, loeschen
Sie bitte diese E-Mail.

***********************************************************************


BITMARCK SOFTWARE GMBH
Paul-Klinger-Strasse 15, 45127 Essen

Amtsgericht Essen HRB 20680
Geschaeftsfuehrer: Frank Krause




--
Daniel C. Sobral

I travel to the future all the time.
Detering Dirk
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
RE: Scala and templates?

Hi Daniel,

> It would ne bice, but have you considering just apply ".text" to the
> xml? You might achieve your goals that way.

no, I think you misunderstood my problem.
It is NOT about generating some form of X-Markup.
It is about generating any form of text, e.g.
for a simple report, an email, or even code.

E.g. currently I have the task to parse an external DSL
with only few productions and generate some
script code from it to let that run in an interpreter.
Too simple to employ external tools like velocity,
but too annoying to describe the artefact in form of
Triple-quoted-String concatenating code.

KR
Det

>
>
> On Wed, Dec 2, 2009 at 1:23 PM, Detering Dirk
> wrote:
>
>
> Hello all,
>
> I would like to hear some opinions/ideas/comments
> regarding templates in Scala.
>
> Every now and then I face the need to create
> textual output, often it is to generate some kind
> of code or report.
>
> One question that arises then is, which template
> engine works seamlessly enough with Scala to
> become the tool of choice?
>
> How does Scala integrate with Velocity, FreeMarker,
> what else?
>
>
> But often the script is so short, it would be oversize
> to use an additional external template system.
>
> Well, Groovy has GStrings, but much more the
> TemplateEngine hierarchy, where the SimpleTemplateEngine
> most often is sufficient for my tasks.
>
> So Groovy has a good backend for text generation, while
> I do the parsing task often by hand with pattern matching
> and switch statements. (KISS principle)
>
> Scala OTOH has a very interesting frontend with the
> parser combinators, allowing to specify parsers as grammars.
>
> But what about the backend? As long as one generates
> XML (HTML) output, there is a tight integration.
>
> The second question is: What about a likewise integrated
> textual construction system?
>
> What I could imagine would be some kind of internal DSL
> or compiler plugin, allowing to construct methods with
> a signature like
> def someTemplate( ):String = {
> .... // template code
> }
>
> But the template code would look more like PHP or JSP or the
> like,
> making the text the main code but with the possibility to escape
> back to scala, to define looping and conditionals.
>
> Would that be doable? Are there perhaps yet any ideas or even
> activities in a comparable direction?
>
> I am eager to hear your opinions about that topic.
>
> KR
> Det
>
>
> --
>
*****************************************************************
> ******
>
> Die Information in dieser E-Mail ist vertraulich und ist
> ausschliesslich
> fuer den/die benannten Adressaten bestimmt. Ein Zugriff auf
diese
> E-Mail durch andere Personen als den/die benannten Adressaten
ist
> nicht gestattet. Sollten Sie nicht der benannte Adressat sein,
> loeschen
> Sie bitte diese E-Mail.
>
>
*****************************************************************
> ******
>
>
> BITMARCK SOFTWARE GMBH
> Paul-Klinger-Strasse 15, 45127 Essen
>
> Amtsgericht Essen HRB 20680
> Geschaeftsfuehrer: Frank Krause
>
>
>
>
>
>
> --
> Daniel C. Sobral
>
> I travel to the future all the time.

dcsobral
Joined: 2009-04-23,
User offline. Last seen 38 weeks 5 days ago.
Re: Scala and templates?
I did understand it. What I'm saying is that you can use XML to give a structure, and then call ".text" on it to retrieve a pure text version. For instance:   def emailXml = <root><headers>{headersXml}</headers>   <body>{bodyXml}</body></root>   def headersXml = <h><to>To: {mail.to}</to> <from>From: {mail.from}</from> {if (!mail.subject.isEmpty) <subject>Subject: {mail.subject}</subject>}</h> 
Etc...   def email = emailXml.text   That will generate not an XML, but a text. The XML is used just to give it structure.
On Wed, Dec 2, 2009 at 3:57 PM, Detering Dirk <Dirk.Detering@bitmarck.de> wrote:
Hi Daniel,

> It would ne bice, but have you considering just apply ".text" to the
> xml? You might achieve your goals that way.

no, I think you misunderstood my problem.
It is NOT about generating some form of X-Markup.
It is about generating any form of text, e.g.
for a simple report, an email, or even code.

E.g. currently I have the task to parse an external DSL
with only few productions and generate some
script code from it to let that run in an interpreter.
Too simple to employ external tools like velocity,
but too annoying to describe the artefact in form of
Triple-quoted-String concatenating code.

KR
Det


>
>
> On Wed, Dec 2, 2009 at 1:23 PM, Detering Dirk
> <Dirk.Detering@bitmarck.de> wrote:
>
>
>       Hello all,
>
>       I would like to hear some opinions/ideas/comments
>       regarding templates in Scala.
>
>       Every now and then I face the need to create
>       textual output, often it is to generate some kind
>       of code or report.
>
>       One question that arises then is, which template
>       engine works seamlessly enough with Scala to
>       become the tool of choice?
>
>       How does Scala integrate with Velocity, FreeMarker,
>       what else?
>
>
>       But often the script is so short, it would be oversize
>       to use an additional external template system.
>
>       Well, Groovy has GStrings, but much more the
>       TemplateEngine hierarchy, where the SimpleTemplateEngine
>       most often is sufficient for my tasks.
>
>       So Groovy has a good backend for text generation, while
>       I do the parsing task often by hand with pattern matching
>       and switch statements. (KISS principle)
>
>       Scala OTOH has a very interesting frontend with the
>       parser combinators, allowing to specify parsers as grammars.
>
>       But what about the backend?  As long as one generates
>       XML (HTML) output, there is a tight integration.
>
>       The second question is: What about a likewise integrated
>       textual construction system?
>
>       What I could imagine would be some kind of internal DSL
>       or compiler plugin, allowing to construct methods with
>       a signature like
>          def  someTemplate( <some params> ):String = {
>               .... // template code
>          }
>
>       But the template code would look more like PHP or JSP or the
> like,
>       making the text the main code but with the possibility to escape
>       back to scala, to define looping and conditionals.
>
>       Would that be doable? Are there perhaps yet any ideas or even
>       activities in a comparable direction?
>
>       I am eager to hear your opinions about that topic.
>
>       KR
>       Det
>
>
>       --
>
*****************************************************************
> ******
>
>       Die Information in dieser E-Mail ist vertraulich und ist
> ausschliesslich
>       fuer den/die benannten Adressaten bestimmt. Ein Zugriff auf
diese
>       E-Mail durch andere Personen als den/die benannten Adressaten
ist
>       nicht gestattet. Sollten Sie nicht der benannte Adressat sein,
> loeschen
>       Sie bitte diese E-Mail.
>
>
*****************************************************************
> ******
>
>
>       BITMARCK SOFTWARE GMBH
>       Paul-Klinger-Strasse 15, 45127 Essen
>
>       Amtsgericht Essen HRB 20680
>       Geschaeftsfuehrer: Frank Krause
>
>
>
>
>
>
> --
> Daniel C. Sobral
>
> I travel to the future all the time.




--
Daniel C. Sobral

I travel to the future all the time.
Dave Griffith
Joined: 2009-01-14,
User offline. Last seen 42 years 45 weeks ago.
Re: Scala and templates?

String interpolation (the equivalent of Groovy GStrings) has been discussed
repeatedly. Last it was left,
the Scala team didn't feel it was worth the extra complexity, and others
respectfully disagreed. It does
seem very odd to allow interpolation in XML literals but not String
literals, but that's the current state of
things.

--Dave Griffith

channingwalton
Joined: 2008-09-27,
User offline. Last seen 2 weeks 1 day ago.
Re: Scala and templates?

Detering Dirk-2 wrote:
>
> I would like to hear some opinions/ideas/comments
> regarding templates in Scala.
>

what about StringTemplate, http://www.stringtemplate.org/, would that be a
good fit?

efleming969
Joined: 2009-01-04,
User offline. Last seen 3 years 22 weeks ago.
Re: Scala and templates?
Jermery Cloud as a template engine called stitchr that is looking nice.

I've been using Freemarker with Scala very successfully.  You can easily create an ObjectWrapper that will allow your templates to use native Scala Maps, Lists, etc.  I also use custom declarations so you can write call Scala functions from your templates.

On Wed, Dec 2, 2009 at 9:23 AM, Detering Dirk <Dirk.Detering@bitmarck.de> wrote:
Hello all,

I would like to hear some opinions/ideas/comments
regarding templates in Scala.

Every now and then I face the need to create
textual output, often it is to generate some kind
of code or report.

One question that arises then is, which template
engine works seamlessly enough with Scala to
become the tool of choice?

How does Scala integrate with Velocity, FreeMarker,
what else?


But often the script is so short, it would be oversize
to use an additional external template system.

Well, Groovy has GStrings, but much more the
TemplateEngine hierarchy, where the SimpleTemplateEngine
most often is sufficient for my tasks.

So Groovy has a good backend for text generation, while
I do the parsing task often by hand with pattern matching
and switch statements. (KISS principle)

Scala OTOH has a very interesting frontend with the
parser combinators, allowing to specify parsers as grammars.

But what about the backend?  As long as one generates
XML (HTML) output, there is a tight integration.

The second question is: What about a likewise integrated
textual construction system?

What I could imagine would be some kind of internal DSL
or compiler plugin, allowing to construct methods with
a signature like
   def  someTemplate( <some params> ):String = {
        .... // template code
   }

But the template code would look more like PHP or JSP or the like,
making the text the main code but with the possibility to escape
back to scala, to define looping and conditionals.

Would that be doable? Are there perhaps yet any ideas or even
activities in a comparable direction?

I am eager to hear your opinions about that topic.

KR
Det


--
***********************************************************************

Die Information in dieser E-Mail ist vertraulich und ist ausschliesslich
fuer den/die benannten Adressaten bestimmt. Ein Zugriff auf diese
E-Mail durch andere Personen als den/die benannten Adressaten ist
nicht gestattet. Sollten Sie nicht der benannte Adressat sein, loeschen
Sie bitte diese E-Mail.

***********************************************************************


BITMARCK SOFTWARE GMBH
Paul-Klinger-Strasse 15, 45127 Essen

Amtsgericht Essen HRB 20680
Geschaeftsfuehrer: Frank Krause


Detering Dirk
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
RE: Scala and templates?

Daniel,

> I did understand it. What I'm saying is that you can use XML to give a
> structure, and then call ".text" on it to retrieve a pure text
version.
> For instance:
>
> def emailXml = {headersXml}
>
> {bodyXml}
>
> def headersXml = To: {mail.to}
> From: {mail.from}
> {if (!mail.subject.isEmpty) Subject:
> {mail.subject}}
>
> Etc...
>
> def email = emailXml.text
>
> That will generate not an XML, but a text. The XML is used just to
give
> it structure.

Nice try, but I consider that not a practical solution but
a specific workaround.
Beside the fact that I did not want to switch String concat
boilerplate with markup boilerplate to "give a structure",
it does not work in all cases.

See:
scala> def versuch = void someMethod() { puts "Hello
World" }
:1: error: ';' expected but string literal found.
def versuch = void someMethod() { puts "Hello
World" }
^

Or:
scala> def versuch = void someMethod() {

:1: error: in XML literal: expected end of Scala block
def versuch = void someMethod() {

That is: One does not straightforward create the artefact but tries
to circumvent the limitations of that approach.

Can btw lead to interesting results:

-----
scala> def methodhead = "void someMethod() {"
methodhead: java.lang.String

scala> def versuch = {methodhead}
versuch: scala.xml.Elem

scala> println (versuch.text)
void someMethod() {
----

YEAH! IT WORKS! Oh, wait, ... I am where I was before: I work with
strings!

Detering Dirk
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
RE: Scala and templates?

Dave Griffith wrote:
> String interpolation (the equivalent of Groovy GStrings) has been
> discussed repeatedly. Last it was left,
> the Scala team didn't feel it was worth the extra complexity, and
> others respectfully disagreed. It does
> seem very odd to allow interpolation in XML literals but not String
> literals, but that's the current state of things.

Well, if it simply is replacing a "tag" with a string like interpolation

works in GString and in Scala XML, I _can_ understand that concatenation
and a smart code format may be a sufficient solution, like Martin
showed:

" This is a text with a ${variable} section in it"
=> " This is a text with a "+variable+" section in it"

Well, this is much uglier for triple-quoted strings:

def report(name:String, orders:List[Order]) = """
Order status report - Customer ordered the following items

"""+salutation(name)+""": """+name+"""

---------------------------------------------------------
"""+orderlist(orders)+"""
---------------------------------------------------------

This report has been created automatically and will not be signed

"""

But interpolation would not allow for conditional and repeated parts.
Consider perhaps something like :

def mytemplate(name:String, orders: List[Order]) = <[
Order status report - Customer ordered the following items

<[if (male(name)) {]>
Mr: <[=name]> and other male related text
<[} else {]>
Mrs: <[=name]> and other female related text
<[}]>

---------------------------------------------------------
<[ orders.each { order => ]>
The order No. <[=order.number]> has the status: <[=order.state]>
<[ } ]>
---------------------------------------------------------

This report has been created automatically and will not be signed
]>

The advantage here is that the whole text is visible in one
place. No need to maintain the order line template or a gender
related line elsewhere, like with the string approach.

If the compiler would be aware of that syntax it could easily
convert it into valid scala code. We could create an external
converter or preprocessor, but that would make the process heavy
and then one could use a template engine anyway.

KR
Det

gdefacci
Joined: 2008-08-21,
User offline. Last seen 2 years 38 weeks ago.
Re: Scala and templates?

I think a solution to template related problems could be making the
startOfScalaExpression character and the endOfScalaExpression
character,
included inside xml expressions, customizable. Maybe something like:

def myTemplate(a:String,b:int):String =

while (i < 0) { // I can use '{'
value = doSomething( %{a}%, 2, %{b}% );
....
}

best regards

G

On 12/3/09, Detering Dirk wrote:
> Dave Griffith wrote:
>> String interpolation (the equivalent of Groovy GStrings) has been
>> discussed repeatedly. Last it was left,
>> the Scala team didn't feel it was worth the extra complexity, and
>> others respectfully disagreed. It does
>> seem very odd to allow interpolation in XML literals but not String
>> literals, but that's the current state of things.
>
> Well, if it simply is replacing a "tag" with a string like interpolation
>
> works in GString and in Scala XML, I _can_ understand that concatenation
> and a smart code format may be a sufficient solution, like Martin
> showed:
>
> " This is a text with a ${variable} section in it"
> => " This is a text with a "+variable+" section in it"
>
> Well, this is much uglier for triple-quoted strings:
>
> def report(name:String, orders:List[Order]) = """
> Order status report - Customer ordered the following items
>
> """+salutation(name)+""": """+name+"""
>
> ---------------------------------------------------------
> """+orderlist(orders)+"""
> ---------------------------------------------------------
>
> This report has been created automatically and will not be signed
>
> """
>
>
> But interpolation would not allow for conditional and repeated parts.
> Consider perhaps something like :
>
> def mytemplate(name:String, orders: List[Order]) = <[
> Order status report - Customer ordered the following items
>
> <[if (male(name)) {]>
> Mr: <[=name]> and other male related text
> <[} else {]>
> Mrs: <[=name]> and other female related text
> <[}]>
>
> ---------------------------------------------------------
> <[ orders.each { order => ]>
> The order No. <[=order.number]> has the status: <[=order.state]>
> <[ } ]>
> ---------------------------------------------------------
>
> This report has been created automatically and will not be signed
> ]>
>
> The advantage here is that the whole text is visible in one
> place. No need to maintain the order line template or a gender
> related line elsewhere, like with the string approach.
>
> If the compiler would be aware of that syntax it could easily
> convert it into valid scala code. We could create an external
> converter or preprocessor, but that would make the process heavy
> and then one could use a template engine anyway.
>
> KR
> Det
>

gdefacci
Joined: 2008-08-21,
User offline. Last seen 2 years 38 weeks ago.
Re: Scala and templates?

I think a solution to template related problems could be making the
startOfScalaExpression character and the endOfScalaExpression
character,
included inside xml expressions, customizable. Maybe something like:

def myTemplate(a:String,b:int):String = {

while (i < 0) { // I can use '{'
value = doSomething( %{a}%, 2, %{b}% );
....
}

best regards

G

On 12/3/09, Detering Dirk wrote:
> Dave Griffith wrote:
>> String interpolation (the equivalent of Groovy GStrings) has been
>> discussed repeatedly. Last it was left,
>> the Scala team didn't feel it was worth the extra complexity, and
>> others respectfully disagreed. It does
>> seem very odd to allow interpolation in XML literals but not String
>> literals, but that's the current state of things.
>
> Well, if it simply is replacing a "tag" with a string like interpolation
>
> works in GString and in Scala XML, I _can_ understand that concatenation
> and a smart code format may be a sufficient solution, like Martin
> showed:
>
> " This is a text with a ${variable} section in it"
> => " This is a text with a "+variable+" section in it"
>
> Well, this is much uglier for triple-quoted strings:
>
> def report(name:String, orders:List[Order]) = """
> Order status report - Customer ordered the following items
>
> """+salutation(name)+""": """+name+"""
>
> ---------------------------------------------------------
> """+orderlist(orders)+"""
> ---------------------------------------------------------
>
> This report has been created automatically and will not be signed
>
> """
>
>
> But interpolation would not allow for conditional and repeated parts.
> Consider perhaps something like :
>
> def mytemplate(name:String, orders: List[Order]) = <[
> Order status report - Customer ordered the following items
>
> <[if (male(name)) {]>
> Mr: <[=name]> and other male related text
> <[} else {]>
> Mrs: <[=name]> and other female related text
> <[}]>
>
> ---------------------------------------------------------
> <[ orders.each { order => ]>
> The order No. <[=order.number]> has the status: <[=order.state]>
> <[ } ]>
> ---------------------------------------------------------
>
> This report has been created automatically and will not be signed
> ]>
>
> The advantage here is that the whole text is visible in one
> place. No need to maintain the order line template or a gender
> related line elsewhere, like with the string approach.
>
> If the compiler would be aware of that syntax it could easily
> convert it into valid scala code. We could create an external
> converter or preprocessor, but that would make the process heavy
> and then one could use a template engine anyway.
>
> KR
> Det
>

Detering Dirk
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
RE: Scala and templates?

> I think a solution to template related problems could be making the
> startOfScalaExpression character and the endOfScalaExpression
> character,
> included inside xml expressions, customizable. Maybe something like:
>
> def myTemplate(a:String,b:int):String =
>
> while (i < 0) { // I can use '{'
> value = doSomething( %{a}%, 2, %{b}% );
> ....
> }
>

I think XML text bodies are simply not for templating text output.
Any effort to extend the XML expressions into this direction would
better be put into a _real_ template like solution.

KR
Det

Maxime Lévesque
Joined: 2009-08-18,
User offline. Last seen 42 years 45 weeks ago.
Re: Scala and templates?

 I fail to understand how string interpolation à la Groovy GStrings
adds complexity.  I'd say that on the contrary this is the kind of
feature that one can understand instantly, and is much much less
verbose than plussing ( "a" + "b" + "...") strings left and right,
perhaps not usefull in all contexts, but priceless for many programming
chores that the programmers have on their schedule...

 Cheers

On Wed, Dec 2, 2009 at 2:04 PM, Dave Griffith <dave.l.griffith@gmail.com> wrote:


String interpolation (the equivalent of Groovy GStrings) has been discussed
repeatedly.   Last it was left,
the Scala team didn't feel it was worth the extra complexity, and others
respectfully disagreed.  It does
seem very odd to allow interpolation in XML literals but not String
literals, but that's the current state of
things.

--Dave Griffith

--
View this message in context: http://old.nabble.com/Scala-and-templates--tp26610699p26614445.html
Sent from the Scala - User mailing list archive at Nabble.com.


dcsobral
Joined: 2009-04-23,
User offline. Last seen 38 weeks 5 days ago.
Re: Scala and templates?
It adds complexity to the compiler, not to the programs.   Personally, I find map and mkString took care of my needs so far, but doing so has been laborious, error-prone, and the result is unreadable.   For instance:   (1)  override def toString = {
    val lineSeparator = ("+"+"-"*5)*3+"+\n"  // That's +-----+-----+-----+, but I arrived at that programmaticaly, and left it so
    (
      (
        repr
        map (
          _.iterator
          grouped 3
          map (_ mkString " ")
          mkString ("|", "|", "|")
        )
      ).iterator
      grouped 3
      map (_ mkString "\n")
      mkString (lineSeparator, "\n"+lineSeparator, "\n"+lineSeparator)
    )
  }   (2)   override def toString = {
    val maxNumSize = self.projection flatMap (_ map (_.toString.size)) reduceLeft (_ max _)
    val numFormat = "%"+maxNumSize+"d"
    def formatNumber(n: Int) = numFormat format n
    val top = rows match {
      case 1 => _row(0) map formatNumber mkString ("< ", " ", " >")
      case _ => _row(0) map formatNumber mkString ("/ ", " ", " \\")
    }
    val middle = rows match {
      case 1 | 2 => Nil
      case _ => self.toList.tail.init map (_ map formatNumber mkString("| "," "," |"))
    }
    val bottom = rows match {
      case 1 => Nil
      case _ => List(_row(rows - 1) map formatNumber mkString ("\\ ", " ", " /"))
    }
   
    top :: middle ::: bottom mkString "\n"
  }
  Powerful, but I doubt anyone figured out the first is a Sudoku board and the second is an integer matrix.   OTOH, complex string output is rather rare in my experience, and simple variable replacement is rather easy to do:   val vars = Map(   "from" -> "do@not.call",   "to" -> "spammers@of.the.world",   "subject" -> "don't" ) val email = """|From: ${FROM}                |To: ${TO}                |Subject: ${SUBJECT}                |                |Please, stop it.""".stripMargin   def subVars(text: String, vars: Map[String, String]) = {   def key2Pattern(key: String) = ("(?i)\\$\\{"+key+"\\}").r   var result = text   for (key <- vars.keys) result = key2Pattern(key).replaceAllIn(result, vars(key))   result }   This particular implementation isn't efficient, but it isn't hard to make an efficient one. So, the only point of string interpolation is when one needs actual code in there, but actual Scala code might not be particularly well-suited to control string interpolation.    Of course, it would be _nice_ to have string interpolation, even if just for simple variable replacement.   So, it all comes down to what the people directly involved with the evolution of the language are used to deal with. Text manipulation, it is not. In fact, text manipulation is so often not a major concern for most programmers not directly involved with operation, that languages such as Awk, Perl and PHP have flourished. Pity, but true.
  2009/12/4 Maxime Lévesque <maxime.levesque@gmail.com>

 I fail to understand how string interpolation à la Groovy GStrings
adds complexity.  I'd say that on the contrary this is the kind of
feature that one can understand instantly, and is much much less
verbose than plussing ( "a" + "b" + "...") strings left and right,
perhaps not usefull in all contexts, but priceless for many programming
chores that the programmers have on their schedule...

 Cheers

On Wed, Dec 2, 2009 at 2:04 PM, Dave Griffith <dave.l.griffith@gmail.com> wrote:


String interpolation (the equivalent of Groovy GStrings) has been discussed
repeatedly.   Last it was left,
the Scala team didn't feel it was worth the extra complexity, and others
respectfully disagreed.  It does
seem very odd to allow interpolation in XML literals but not String
literals, but that's the current state of
things.

--Dave Griffith

--
View this message in context: http://old.nabble.com/Scala-and-templates--tp26610699p26614445.html
Sent from the Scala - User mailing list archive at Nabble.com.





--
Daniel C. Sobral

I travel to the future all the time.
Detering Dirk
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
RE: Scala and templates?

> OTOH, complex string output is rather rare in my experience,

In my experience it is not, but that may be a typical MDSD/MDA
developer's attitude. Code generation and report generation is
daily business here. Reg. the latter: in a mixed unix-o-philes
and win-o-philes environment grep/awk/sed based shell scripts
aren't the way to share text analysing algorithms.
JVM is the common setting, and that is why we now appreciate Groovy
as sharing language for such stuff.

> and simple
> variable replacement is rather easy to do:
> [..snipped some complicated variable substitution code..]
> [..snipped more ...]
> Of course, it would be _nice_ to have string interpolation, even if
> just for simple variable replacement.

To be honest, I slapped my forehead this morning and based on intuition
looked up the RichString docs. And really: The solution for THAT example
is simple:

val email = """|From: %s
|To: %s
|Subject: %s
|
|Please, stop it.""".stripMargin

val resolution = email.format("Peter", "Frank", "Just a test")

It's based on positional parameters, but so what?
Weird, that no one mentioned that in this thread before...

KR
Det

dcsobral
Joined: 2009-04-23,
User offline. Last seen 38 weeks 5 days ago.
Re: Scala and templates?
Actually, I assumed you knew of and was not interested in that solution, precisely because it is based on positional parameters.

2009/12/7 Detering Dirk <Dirk.Detering@bitmarck.de>
> OTOH, complex string output is rather rare in my experience,

In my experience it is not, but that may be a typical MDSD/MDA
developer's attitude. Code generation and report generation is
daily business here. Reg. the latter: in a mixed unix-o-philes
and win-o-philes environment  grep/awk/sed based shell scripts
aren't the way to share text analysing algorithms.
JVM is the common setting, and that is why we now appreciate Groovy
as sharing language for such stuff.

> and simple
> variable replacement is rather easy to do:
> [..snipped some complicated variable substitution code..]
> [..snipped more ...]
> Of course, it would be _nice_ to have string interpolation, even if
> just for simple variable replacement.

To be honest, I slapped my forehead this morning and based on intuition
looked up the RichString docs. And really:  The solution for THAT example
is simple:

val email = """|From: %s
              |To: %s
              |Subject: %s
              |
              |Please, stop it.""".stripMargin

val resolution = email.format("Peter", "Frank", "Just a test")

It's based on positional parameters, but so what?
Weird, that no one mentioned that in this thread before...

KR
Det






--
Daniel C. Sobral

I travel to the future all the time.
Randall R Schulz
Joined: 2008-12-16,
User offline. Last seen 1 year 29 weeks ago.
Re: Scala and templates?

On Monday December 7 2009, Daniel Sobral wrote:
> Actually, I assumed you knew of and was not interested in that
> solution, precisely because it is based on positional parameters.

Read the JavaDoc for format more closely. You are not limited to
positional parameters. I.e., the %whatever includes a means of taking
an arbitrary argument from the parameter list by index. Thus the order
of interpolations into the format string need not be the same as the
order of the arguments to format.

Randall Schulz

Dave Griffith
Joined: 2009-01-14,
User offline. Last seen 42 years 45 weeks ago.
Re: Scala and templates?

A functionality that seems almost purposely designed to create obfuscated
code...

--Dave Griffith

Randall R Schulz
Joined: 2008-12-16,
User offline. Last seen 1 year 29 weeks ago.
Re: Scala and templates?

On Monday December 7 2009, Dave Griffith wrote:
> A functionality that seems almost purposely designed to create
> obfuscated code...

I don't know why you say so.

I see it as a way to allow just the sort of flexible interpolation that
is sought here. The API tells the client the positions of each argument
and client gets to synthesize a format string that can reliably access
those arguments in random-access fashion.

> --Dave Griffith

Randall Schulz

Igor Khlystov
Joined: 2009-12-07,
User offline. Last seen 42 years 45 weeks ago.
Re: Scala and templates?

An example of home made string interpolation

http://tinyurl.com/ykyk5zy

Detering Dirk-2 wrote:
>
> Hello all,
>
> I would like to hear some opinions/ideas/comments
> regarding templates in Scala.
>
> ...
>
>

Dave Griffith
Joined: 2009-01-14,
User offline. Last seen 42 years 45 weeks ago.
Re: Scala and templates?

Randall Schulz wrote:
>
> I don't know why you say so.
>

Code is read many more times than it is written. Understanding a format
string with no positional
annotations requires scanning through two lists in parallel. This is
requires maintaining one piece of
context in mind, which is annoying, but doable. Understanding a format
string with positional
annotations requires complex mental counting and cross-indexing. Much more
context needs to
be maintained, hence the task much more difficult, slower, and more
error-prone. Conversely,
understanding native string interpolation (e.g. Groovy GStrings) can be done
without maintaining
any mental context at all.

This is all Cognitive Psych 101 stuff.

Anyone who says complex string formatting isn't common hasn't spent much
time in enterprise
software, and probably slept through the last fifteen years of the web.

--Dave Griffith

Randall R Schulz
Joined: 2008-12-16,
User offline. Last seen 1 year 29 weeks ago.
Re: Scala and templates?

On Monday December 7 2009, Igor Khlystov wrote:
> An example of home made string interpolation
>
> http://tinyurl.com/ykyk5zy

Ugh. Reflection.

I still think Scala deserves some kind of metaprogramming facility, as
non-trivial as that would be to design and implement. Something
inspired by Haskell's template mechanism, perhaps, though I know very
little about that yet.

Randall Schulz

Randall R Schulz
Joined: 2008-12-16,
User offline. Last seen 1 year 29 weeks ago.
Re: Scala and templates?

On Monday December 7 2009, Dave Griffith wrote:
> Randall Schulz wrote:
> > I don't know why you say so.
>
> Code is read many more times than it is written.

I'm not so sure how true that really is,
though "many" is pretty imprecise.

> ...

You seem a little touchy about this.

> --Dave Griffith

Randall Schulz

Dave Griffith
Joined: 2009-01-14,
User offline. Last seen 42 years 45 weeks ago.
Re: Scala and templates?

Randall Schulz wrote:
>
> You seem a little touchy about this.
>

Not at all. This is just one place where Scala has a really obvious and
fixable gap which, if fixed,
would increase it's usefulness to a large user community. This would be
fine (every language design
has to make tradeoffs), if Scala didn't already have XML interpolation,
which is basically the same
functionality but differently specialized and arguably less useful.

--Dave Griffith

Randall R Schulz
Joined: 2008-12-16,
User offline. Last seen 1 year 29 weeks ago.
Re: Scala and templates?

On Monday December 7 2009, Dave Griffith wrote:
> Randall Schulz wrote:
> > You seem a little touchy about this.
>
> Not at all. This is just one place where Scala has a really obvious
> and fixable gap which, if fixed, would increase it's usefulness to a
> large user community. This would be fine (every language design
> has to make tradeoffs), if Scala didn't already have XML
> interpolation, which is basically the same functionality but
> differently specialized and arguably less useful.

Well, I agree about this, to be sure. I just don't denigrate the
positional argument notation in java.util.Formatter.

> --Dave Griffith

Randall Schulz

dcsobral
Joined: 2009-04-23,
User offline. Last seen 38 weeks 5 days ago.
Re: Scala and templates?
Dave, I have done nothing *but* enterprise software, in the last 9 years, and while there's a some string manipulation going on in them, it's the trivial kind. The Java code I have here mostly uses StringBuilder appends, though here and there one can find manual interpolation (ie, 5 lines involving regex) -- and usually in places where the correct thing to do would be using an XML library.   String interpolation would make this stuff more clean, but the impact would be negligible. That's simply not where the complexity is, and manipulating three or four variables to be interpolated is just plain too simple.
  Now, if one would build XMLs through string interpolation, I'd grant it would definitely create a lot of complex cases -- but I argue that's the case of someone who wants a better hammer to deal with a problem that should be solved with a screwdriver. I assume that is not the case for you, as you'd just use XML literals.   I honestly don't see where one would use much complex string manipulation of the kind that makes use of string interpolation. Someone (you?) mentioned code generation, and I can definitely see it there, though I'm curious about how one would heavily use code generation (and, I'll admit, I suspect code generation in first place).   But whatever might be my experience or yours, it's the rare person who I see inquiring about string interpolation in Scala. Maybe people who use that a lot works with Ruby or Groovy and Scala is just not their things -- and, in that case, I suspect the heavy use of string interpolation would be more of a case of having a hammer than needing one. But, barring that, I can only conclude it is rare.   Please, _do_ note I'm not saying it is not a useful thing. It is, it makes code cleaner, and it's ridiculous to have it for XML but not for String.   On a related note, at scala-debate I proposed a new method for Scala's Regex that would enable one to do this:   def qr(s: String) = "${"+s+"}" val vars = Map(qr("from") -> "from@myself", qr("to") -> "spammer@new", qr("subject") -> "Stop it") val emailRaw = """|From: ${from}                   |To: ${to}                   |Subject: ${subject}                   |                   |Email text""".stripMargin val email = "(?i)\{\w+\}".r replace (emailRaw, vars)   Would that be better?   On Mon, Dec 7, 2009 at 1:50 PM, Dave Griffith <dave.l.griffith@gmail.com> wrote:



Randall Schulz wrote:
>
> I don't know why you say so.
>

Code is read many more times than it is written.  Understanding a format
string with no positional
annotations requires scanning through two lists in parallel.  This is
requires maintaining one piece of
context in mind, which is annoying, but doable.  Understanding a format
string with positional
annotations requires complex mental counting and cross-indexing.  Much more
context needs to
be maintained, hence the task much more difficult, slower, and more
error-prone.  Conversely,
understanding native string interpolation (e.g. Groovy GStrings) can be done
without maintaining
any mental context at all.

This is all Cognitive Psych 101 stuff.

Anyone who says complex string formatting isn't  common hasn't spent much
time in enterprise
software, and probably slept through the last fifteen years of the web.

--Dave Griffith

--
View this message in context: http://old.nabble.com/Scala-and-templates--tp26610699p26679215.html
Sent from the Scala - User mailing list archive at Nabble.com.




--
Daniel C. Sobral

I travel to the future all the time.
geoff
Joined: 2008-08-20,
User offline. Last seen 1 year 25 weeks ago.
Re: Scala and templates?

A functionality that seems almost purposely designed to allow localized
messages...

Fixed that for you. In English the desired formatted string might be
"Downloaded 10 of 100 messages" using the format "Downloaded %d of %d
messages". Consider another language where the proper sentence structure
might be "Of 100 messages 10 are downloaded" then the format string
would be "Of %2$d messages %1$d are downloaded".

Back to the main topic of the thread, here's something that works a bit
like groovy GStrings:

trait SStringSegment {
def appendTo(b: StringBuffer): Unit
}

class SString(segs: Seq[SStringSegment]) extends SStringSegment {
override def toString = {
val buf = new StringBuffer
appendTo(buf)
buf.toString
}

def appendTo(b: StringBuffer) { segs.foreach(_.appendTo(b)) }
}

object SString {
def apply(segs: SStringSegment*) = new SString(segs)
}

trait ExtraLowPrioritySStringImplicits {
implicit def any2seg(a: Any): SStringSegment = new SStringSegment {
def appendTo(b: StringBuffer) { b.append(a.toString) }
}
}

trait LowPrioritySStringImplicits extends ExtraLowPrioritySStringImplicits {
implicit def f02seg(f: Function0[Any]): SStringSegment = new SStringSegment {
def appendTo(b: StringBuffer) { b.append(f().toString) }
}
}

object SStringSegment extends LowPrioritySStringImplicits {
implicit def string2seg(s: String): SStringSegment = new SStringSegment {
def appendTo(b: StringBuffer) { b.append(s) }
}

implicit def f12seg(f: StringBuffer => Any): SStringSegment = new SStringSegment {
def appendTo(b: StringBuffer) { f(b) }
}

implicit def f0seg2seg(f: Function0[SStringSegment]): SStringSegment = new SStringSegment {
def appendTo(b: StringBuffer) { f().appendTo(b) }
}

}

then you can do

SString("It is currently ",new java.util.Date())

or

SString("It is currently ",()=>new java.util.Date())

or

SString("It is currently ",(buf:StringBuffer)=>buf.append(new java.util.Date()))

or

def now = SString(new java.util.Date())

SString("It is currently ",now)

or

def now = SString(new java.util.Date())

SString("It is currently ",now _)

bord
Joined: 2008-09-19,
User offline. Last seen 4 years 5 weeks ago.
Re: Scala and templates?

as mentioned on the website tinyurl....
having to constantly escape &, <, > in the xml (for use with .totext) was
"ruining my day",
i.e. making my template code too hard to read
(note i have need to ouput C++ template code, so i had plenty of <> to deal
with)
I hit on an improvement to deal with some of the escape needs.
so instead of the two bad choices
< or {"<"} littering my xml code, i opted for just {>} in my xml code
from voila

val < = "<"

I guess you could say i have my own little DSL for <, >, & now thanks to
Scala.
still,
At the end of the day, i really could use string interpolation in scala
similar to the xml expression handling, but i'm coping with xml .totext with
some crutches and suffering some performance loss but at least it beats
"..."+...+"... and to/mkStrings
bord
ps. the article at the tinyurl site was interesting and i can say that i
considered something like it, but i wanted full freedom of any scala
expression in the interpolation.

Igor Khlystov wrote:
>
> An example of home made string interpolation
>
> http://tinyurl.com/ykyk5zy
>
>
>
> Detering Dirk-2 wrote:
>>
>> Hello all,
>>
>> I would like to hear some opinions/ideas/comments
>> regarding templates in Scala.
>>
>> ...
>>
>>
>
>

James.Strachan
Joined: 2009-07-08,
User offline. Last seen 2 years 25 weeks ago.
Re: Scala and templates?

Sorry to bring an old thread back to life, but I've finally got an answer
:)...

Detering Dirk-2 wrote:
>
> Hello all,
>
> I would like to hear some opinions/ideas/comments
> regarding templates in Scala.
>
> Every now and then I face the need to create
> textual output, often it is to generate some kind
> of code or report.
>
> One question that arises then is, which template
> engine works seamlessly enough with Scala to
> become the tool of choice?
>

I've been hacking lately on Scalate which is a Scala based template engine
which could be considered a pure Scala alternative to
Velocity/FreeMarker/JSP/Erb/HAML

http://scalate.fusesource.org/

The basic idea is to use the Scala language for all expressions and control
flow; then use SSP (JSP/ERb like syntax) for string interpolation or Scaml
(HAML syntax) for markup interpolation.

Whichever template syntax is used, the templates are statically typed, so at
edit/compile time you know if you've any errors in your template expressions
(unlike Velocity/FreeMarker/JSP/Erb/HAML).

Detering Dirk-2 wrote:
>
> But often the script is so short, it would be oversize
> to use an additional external template system.
>
> Well, Groovy has GStrings, but much more the
> TemplateEngine hierarchy, where the SimpleTemplateEngine
> most often is sufficient for my tasks.
>
> So Groovy has a good backend for text generation, while
> I do the parsing task often by hand with pattern matching
> and switch statements. (KISS principle)
>
> Scala OTOH has a very interesting frontend with the
> parser combinators, allowing to specify parsers as grammars.
>

Agreed. The parsers for SSP and Scaml are both implemented using Scala's
parser combinators...

http://github.com/scalate/scalate/blob/master/scalate-core/src/main/scal...
http://github.com/scalate/scalate/blob/master/scalate-core/src/main/scal...

I'm still amazed by how tiny the SspParser is :)

If someone has a particular template syntax they prefer it should be trivial
to add another syntax option to Scalate. (e.g. Velocity style for example).
There are a lot of different template language flavours that different folks
like.

Detering Dirk-2 wrote:
>
> The second question is: What about a likewise integrated
> textual construction system?
>
> What I could imagine would be some kind of internal DSL
> or compiler plugin, allowing to construct methods with
> a signature like
> def someTemplate( ):String = {
> .... // template code
> }
>
> But the template code would look more like PHP or JSP or the like,
> making the text the main code but with the possibility to escape
> back to scala, to define looping and conditionals.
>

There's a simple API you can use right now.

val engine = new TemplateEngine
val template = engine.compileSsp("some template text...")
val output = engine.layout(template, Map("param1" -> 5))

you can refer to templates by URI or provide their text; then render them to
a context or grab it as a String etc.

More detail on using the API directly here:
http://scalate.fusesource.org/documentation/scalate-embedding-guide.html

James

nilskp
Joined: 2009-01-30,
User offline. Last seen 1 year 27 weeks ago.
Re: Scala and templates?
On Wed, Mar 31, 2010 at 8:11 AM, James.Strachan <james.strachan@gmail.com> wrote:
I've been hacking lately on Scalate which is a Scala based template engine
which could be considered a pure Scala alternative to
Velocity/FreeMarker/JSP/Erb/HAML

http://scalate.fusesource.org/


Scaladocs?

James.Strachan
Joined: 2009-07-08,
User offline. Last seen 2 years 25 weeks ago.
Re: Scala and templates?

Nils Kilden-Pedersen wrote:
>
> On Wed, Mar 31, 2010 at 8:11 AM, James.Strachan
> wrote:
>
>> I've been hacking lately on Scalate which is a Scala based template
>> engine
>> which could be considered a pure Scala alternative to
>> Velocity/FreeMarker/JSP/Erb/HAML
>>
>> http://scalate.fusesource.org/
>>
>>
> Scaladocs?
>

Unfortunately I've not yet figured out the ninja to get scaladocs
working with maven-scala-plugin and Scala 2.8.0-beta1 - I'll try get
that sorted ASAP, sorry!

James

david.bernard
Joined: 2009-01-08,
User offline. Last seen 1 year 27 weeks ago.
Re: Scala and templates?

you need version 2.13.2-SNAPSHOT of maven-scala-plugin to generate scaladoc2.
http://groups.google.com/group/maven-and-scala/browse_thread/thread/eeef...

/davidB

On Wed, Mar 31, 2010 at 20:23, James.Strachan wrote:
>
>
>
> Nils Kilden-Pedersen wrote:
>>
>> On Wed, Mar 31, 2010 at 8:11 AM, James.Strachan
>> wrote:
>>
>>> I've been hacking lately on Scalate which is a Scala based template
>>> engine
>>> which could be considered a pure Scala alternative to
>>> Velocity/FreeMarker/JSP/Erb/HAML
>>>
>>> http://scalate.fusesource.org/
>>>
>>>
>> Scaladocs?
>>
>
> Unfortunately I've not yet figured out the ninja to get scaladocs
> working with maven-scala-plugin and Scala 2.8.0-beta1 - I'll try get
> that sorted ASAP, sorry!
>
> James
> --
> View this message in context: http://old.nabble.com/Scala-and-templates--tp26610699p28099885.html
> Sent from the Scala - User mailing list archive at Nabble.com.
>
>

nilskp
Joined: 2009-01-30,
User offline. Last seen 1 year 27 weeks ago.
Re: Scala and templates?
On Wed, Mar 31, 2010 at 8:11 AM, James.Strachan <james.strachan@gmail.com> wrote:
I've been hacking lately on Scalate which is a Scala based template engine
which could be considered a pure Scala alternative to
Velocity/FreeMarker/JSP/Erb/HAML

http://scalate.fusesource.org/

I haven't spent too much time looking, but from all the examples it seems that templates can only be loaded from files and/or URI strings. Is that correct? If so I would urge you to add support for something more generic, say java.io.Reader, InputStream, or scala.io.Source. This is more flexible and you can always add an implicit conversion to turn a File into either one.
Dave Griffith
Joined: 2009-01-14,
User offline. Last seen 42 years 45 weeks ago.
Re: Scala and templates?

Having spent much of the last six weeks porting a production JAX-RS web
service to use FreeMarker for output, I have to say that this looks
promising, but not quite there yet. My darn-near-ideal web stack would look
something like Scala +JAX-RS+(hypothetical strongly-typed, Scala-aware
IBatis)+(hypothetical strongly-typed, Scala-aware FreeMarker)+JQuery.
(Notice that neither Spring nor Hibernate makes the cut). Scalate has two
different templating languages, each of which covers half of the use case
very well and leaves the rest hanging. The first has both a new (and
somewhat ugly) syntax and only covers XHTML, and the second reprises all of
the well known failure modes of ASP/JSP/GSP, with minimal upside over them.
I can understand the value of each of them, but I'm afraid they lose out to
FreeMarker for me, simply for its clarity and control. Give me a templating
language where the code looks like the output (minimal to no escaping), can
enforce strong typing of its inputs, allows unit testing (no *SP need
apply), and lets me create a controlled code vocabulary (no arbitrary code
insertion), and I'll be a very happy man indeed. It's a tricky problem, but
there's no reason a solution shouldn't be possible given Scala's power.

Nils Kilden-Pedersen wrote:
>
> On Wed, Mar 31, 2010 at 8:11 AM, James.Strachan
> wrote:
>
>> I've been hacking lately on Scalate which is a Scala based template
>> engine
>> which could be considered a pure Scala alternative to
>> Velocity/FreeMarker/JSP/Erb/HAML
>>
>> http://scalate.fusesource.org/
>>
>
> I haven't spent too much time looking, but from all the examples it seems
> that templates can only be loaded from files and/or URI strings. Is that
> correct? If so I would urge you to add support for something more generic,
> say java.io.Reader, InputStream, or scala.io.Source. This is more flexible
> and you can always add an implicit conversion to turn a File into either
> one.
>
>

James.Strachan
Joined: 2009-07-08,
User offline. Last seen 2 years 25 weeks ago.
Re: Scala and templates?

On 31 March 2010 21:54, David Bernard wrote:
> you need version 2.13.2-SNAPSHOT of maven-scala-plugin to generate scaladoc2.
> http://groups.google.com/group/maven-and-scala/browse_thread/thread/eeef...

Thanks David! I did try that but still got errors - I'll report it on
the maven-scala-plugin list to save the noise here.

James.Strachan
Joined: 2009-07-08,
User offline. Last seen 2 years 25 weeks ago.
Re: Scala and templates?

On 1 April 2010 01:32, Nils Kilden-Pedersen wrote:
> On Wed, Mar 31, 2010 at 8:11 AM, James.Strachan
> wrote:
>>
>> I've been hacking lately on Scalate which is a Scala based template engine
>> which could be considered a pure Scala alternative to
>> Velocity/FreeMarker/JSP/Erb/HAML
>>
>> http://scalate.fusesource.org/
>
> I haven't spent too much time looking, but from all the examples it seems
> that templates can only be loaded from files and/or URI strings. Is that
> correct?

This would probably be a bit more clear when we've got the scaladocs
working, but there's a few methods on TemplateEngine for compiling a
template from text; where the entire template definition is the
content of a single String; though we've not yet overloaded those to
work with reader/streams/source though.

e.g.

// a template with an attribute
val source = "<%@ val name: String %> hello ${name}"

val template = engine.compileSsp(source)
val output = engine.layout(template, Map("name" -> "James"))

// test it works...
expect("hello James") {output}

A few more test cases might help you get an idea for whats possible (I
just added a few more of file/text samples)...
http://github.com/scalate/scalate/blob/master/scalate-core/src/test/scal...

I just added a load method that takes a File too.

> If so I would urge you to add support for something more generic,
> say java.io.Reader, InputStream, or scala.io.Source. This is more flexible
> and you can always add an implicit conversion to turn a File into either
> one.

Good point Nils. We currently use the URI to guess the extension (for
the template style) and package (to make it easier to put templates
inside a package using naming conventions to avoid unnecessary imports
- which is particularly handy when using Scalate as a view layer for
resources/controllers/DTOs/models when using JAXRS or Spring MVC type
stuff).

We should maybe introduce a little class (like Source from Java's TrAX
API) which wraps up how to load the text of the template and how get
the package name & extension, so its easier for folks to feed in
Reader/InputStream/Source with a package & extension.

James.Strachan
Joined: 2009-07-08,
User offline. Last seen 2 years 25 weeks ago.
Re: Scala and templates?

Dave Griffith wrote:
>
> Having spent much of the last six weeks porting a production JAX-RS web
> service to use FreeMarker for output, I have to say that this looks
> promising, but not quite there yet. My darn-near-ideal web stack would
> look something like Scala +JAX-RS+(hypothetical strongly-typed,
> Scala-aware IBatis)+(hypothetical strongly-typed, Scala-aware
> FreeMarker)+JQuery.
>

I'm a Scala + JAXRS fan too :). My main use case for Scalate was an
alternative to JSP on a bunch of Scala JAXRS web apps....

Dave Griffith wrote:
>
> (Notice that neither Spring nor Hibernate makes the cut). Scalate has
> two different templating languages, each of which covers half of the use
> case very well and leaves the rest hanging. The first has both a new
> (and somewhat ugly) syntax and only covers XHTML,
>

Scaml/Haml is definitely an acquired taste (as is Scala too - at first it
can look a little weird/ugly until you get it). Scaml works for any markup
really HTML/XML/XHTML. Its very DRY and concise - particularly when you
compare like-for-like templates in different languages; after being a bit of
a Haml-sceptic I've certainly fallen for it (its one of the few
indention-sensitive languages I really like ;-). The use of indention for
markup tag open/close and for code blocks works really well in template
engines (since the code is simple) - I'm not a fan of indentation sensitive
programming languages though since they are way more complex.

Using a single token = and some indentation makes it super easy to use Scala
syntax for logical branching for example...

%table
= for (person in people)
%tr
%td
= person.name
%td
= person.location

% means element, = means scala expression. Very little syntax noise etc. So
very little magic syntax like #if (someOtherExpressionLanguage).

The real sweet spot of Scaml is generating HTML/XHTML though really using
the CSS #id and .class syntaxes to make even more concise markup which has
CSS classes and IDs applied.

Dave Griffith wrote:
>
> and the second reprises all of the well known failure modes of
> ASP/JSP/GSP, with minimal upside over them.
>

SSP is kinda a Scala port of Erb/JSP/ASP - its kinda designed to feel
similar if you've used those and know them well.

The upside of SSP over the others is its using Scala rather than
Ruby/Java/EL/whatever and each template is statically typed; plus you can
invoke any Scala method to return markup. It also misses out a ton of legacy
crap from JSP so its much simpler, yet more powerful (as you can easily pass
blocks of template to a Scala method to create pseudo custom tags like in
JSP.

In many ways SSP is tiny; since Scala does all the heavy lifting. All SSP is
really is the minimal set of interpolation tokens (using the same ones from
JSP/Erb) which lets you mix regular Scala syntax for expressions, logical
branching and looping with a template.

Dave Griffith wrote:
>
> I can understand the value of each of them, but I'm afraid they lose out
> to FreeMarker for me, simply for its clarity and control.
>

There are so many different use cases in templates; depending on the skills,
knowledge and personal tastes of the individual who's editing the templates
and how close to the output format they want them to look versus how DRY
they want or how powerful and concise the expressions/directives are. Just
like there are multiple programming languages suited to different needs, I
see the need for different template languages based on your exact
requirements.

We specifically engineered Scalate so that its super easy to add different
surface syntax & create a new flavour of template engine. For example Ssp
and Scaml seem very different, but really are mostly different parsers and
slightly different code generators; much of them is exactly the same.

So a FreeMarker/Velocity style surface syntax is easily possible for example
- since really a Scalate FreeMarker/Velocity would really mostly be just a
different parser on top of mostly the same Ssp engine. For example here's
all the SSP specific code...
http://github.com/scalate/scalate/tree/master/scalate-core/src/main/scal...

and here's the SspParser...
http://github.com/scalate/scalate/blob/master/scalate-core/src/main/scal...

FreeMarker uses the same interpolation ${foo} as Ssp; its mostly the tags of
FreeMarker thats different. So instead of Ssp's

<% if (x == 5) {%>
blah
<% } %>

it would be something like this in FreeMarker

<#if x == 5 >
blah

Note since Scalate uses Scala for expressions, you can use if/else in an
interpolation expression in Ssp

${ if (x == 5) "blah" else "" }

So in a long round about way I'm saying it should be pretty easy to add a
FreeMarker/Velocity style parser to Scalate if you fancy - I'll gladly help
out if you want.

Dave Griffith wrote:
>
> Give me a templating language where the code looks like the output
> (minimal to no escaping), can enforce strong typing of its inputs, allows
> unit testing (no *SP need apply),
>

*SP matches SSP :) You can easily unit test SSP scripts in a unit test
without any web container or anything if thats what you mean...
http://github.com/scalate/scalate/blob/master/scalate-core/src/test/scal...

Dave Griffith wrote:
>
> and lets me create a controlled code vocabulary (no arbitrary code
> insertion), and I'll be a very happy man indeed. It's a tricky problem,
> but there's no reason a solution shouldn't be possible given Scala's
> power.
>

Totally agree. Though it seems everyone has a different set of often quite
different requirements so its quite hard for there to be one template engine
to rule them all.

Could you explain a bit more what you mean by a controlled code vocabulary
(no arbitrary code insertion)? Its kinda a double edge sword. You can have a
really simple restricted expression language like EL - which doesn't even
let you call a method on domain object (or the EL in Velocity/FreeMarker
which are less restrictive), or if you support Scala expressions you get
immense power and conciseness (and static typing) - but that means you can
pretty much do anything in Scala.

James.Strachan
Joined: 2009-07-08,
User offline. Last seen 2 years 25 weeks ago.
Re: Scala and templates?

On 31 March 2010 17:58, Nils Kilden-Pedersen wrote:
> On Wed, Mar 31, 2010 at 8:11 AM, James.Strachan
> wrote:
>>
>> I've been hacking lately on Scalate which is a Scala based template engine
>> which could be considered a pure Scala alternative to
>> Velocity/FreeMarker/JSP/Erb/HAML
>>
>> http://scalate.fusesource.org/
>
> Scaladocs?

After some great help from David Bernard on the maven-scala-plugin
list here you go...
http://scalate.fusesource.org/maven/1.0-SNAPSHOT/scalate-core/scaladocs/...

The above is the main package which is all you really need to use the
API explicitly rather than just hacking templates and using
Play/Servlets/JAXRS/Jersey.

Unfortunately scaladocs shows exceptions like any other class, so the
root package looks a bit crowded :(.

TemplateEngine is really all you need :)
http://scalate.fusesource.org/maven/1.0-SNAPSHOT/scalate-core/scaladocs/...

The full scaladocs are here (only really relevent if you want to hack
a filter/layout/console plugin or work on integration with
servlets/jersey or look at the implementation detail etc)
http://scalate.fusesource.org/maven/1.0-SNAPSHOT/scalate-core/scaladocs/...

Dave Griffith
Joined: 2009-01-14,
User offline. Last seen 42 years 45 weeks ago.
Re: Scala and templates?

James.Strachan wrote:
>
> Scaml/Haml is definitely an acquired taste (as is Scala too - at first it
> can look a little weird/ugly until you get it). Scaml works for any markup
> really HTML/XML/XHTML.
>

I can absolutely see this for XML returned from web services, and would
definitely appreciate something like it for JSON as well, but for general
XHTML it seems like it would get too deeply nested too quickly.

James.Strachan wrote:
>
> You can easily unit test SSP scripts in a unit test without any web
> container or anything if thats what you mean...
>

Excellent. That's half of my issue with JSPs covered right there.

James.Strachan wrote:
>
> Could you explain a bit more what you mean by a controlled code vocabulary
> (no arbitrary code insertion)? Its kinda a double edge sword. You can have
> a really simple restricted expression language like EL - which doesn't
> even let you call a method on domain object (or the EL in
> Velocity/FreeMarker which are less restrictive), or if you support Scala
> expressions you get immense power and conciseness (and static typing) -
> but that means you can pretty much do anything in Scala.
>

By controlled code vocabulary, I'm mostly thinking again of FreeMarker. I
can't embed arbitrary Java code into FreeMarker, and I strongly prefer it
that way. What I can do is extend the tag language that FreeMarker provides
with simple tags (implemented either in Java or FreeMarker) or extend the
expression language with simple methods (implemented in Java). Those tags
and expressions can be tested in isolation, and don't allow the opportunity
for arbitrary business logic to infect code. It's a middle ground between
simple interpolation and uncontrolled code injection, and it goes a long way
to enforce separation of concerns. Enforcing something like this in a
strongly-typed fashion is pretty much the last step to my ideal templating
solution.

--Dave Griffith

Oscar Forero 2
Joined: 2010-01-18,
User offline. Last seen 42 years 45 weeks ago.
Re: Scala and templates?

Hello,

I was wondering how do you include FreeMarker or StringTemplate into a Scala application build process.
I want to generate some Scala classes from a template an an input and then compile them.

Do any of those tools have Maven plugins that could be used out of the box?

regards,

Oscar

On Apr 5, 2010, at 3:16 PM, Dave Griffith wrote:

>
>
>
> James.Strachan wrote:
>>
>> Scaml/Haml is definitely an acquired taste (as is Scala too - at first it
>> can look a little weird/ugly until you get it). Scaml works for any markup
>> really HTML/XML/XHTML.
>>
>
> I can absolutely see this for XML returned from web services, and would
> definitely appreciate something like it for JSON as well, but for general
> XHTML it seems like it would get too deeply nested too quickly.
>
>
> James.Strachan wrote:
>>
>> You can easily unit test SSP scripts in a unit test without any web
>> container or anything if thats what you mean...
>>
>
> Excellent. That's half of my issue with JSPs covered right there.
>
>
> James.Strachan wrote:
>>
>> Could you explain a bit more what you mean by a controlled code vocabulary
>> (no arbitrary code insertion)? Its kinda a double edge sword. You can have
>> a really simple restricted expression language like EL - which doesn't
>> even let you call a method on domain object (or the EL in
>> Velocity/FreeMarker which are less restrictive), or if you support Scala
>> expressions you get immense power and conciseness (and static typing) -
>> but that means you can pretty much do anything in Scala.
>>
>
> By controlled code vocabulary, I'm mostly thinking again of FreeMarker. I
> can't embed arbitrary Java code into FreeMarker, and I strongly prefer it
> that way. What I can do is extend the tag language that FreeMarker provides
> with simple tags (implemented either in Java or FreeMarker) or extend the
> expression language with simple methods (implemented in Java). Those tags
> and expressions can be tested in isolation, and don't allow the opportunity
> for arbitrary business logic to infect code. It's a middle ground between
> simple interpolation and uncontrolled code injection, and it goes a long way
> to enforce separation of concerns. Enforcing something like this in a
> strongly-typed fashion is pretty much the last step to my ideal templating
> solution.
>
> --Dave Griffith
>

Brian Clapper
Joined: 2009-05-18,
User offline. Last seen 42 years 45 weeks ago.
Re: Scala and templates?

Dave Griffith wrote:

> By controlled code vocabulary, I'm mostly thinking again of FreeMarker. I
> can't embed arbitrary Java code into FreeMarker, and I strongly prefer it
> that way. What I can do is extend the tag language that FreeMarker provides
> with simple tags (implemented either in Java or FreeMarker) or extend the
> expression language with simple methods (implemented in Java). Those tags
> and expressions can be tested in isolation, and don't allow the opportunity
> for arbitrary business logic to infect code. It's a middle ground between
> simple interpolation and uncontrolled code injection, and it goes a long way
> to enforce separation of concerns. Enforcing something like this in a
> strongly-typed fashion is pretty much the last step to my ideal templating
> solution.

I find myself looking for a Scala template language that meets the same
criteria. I don't want a template language that allows arbitrary code
insertion, for the reasons that include the ones Dave Griffith outlines.
StringTemplate is appealing, but it'd be nice to have something more
Scala-friendly. (I'm considering writing some Scala wrappers for
StringTemplate, in fact.)

The ability to insert arbitrary Scala code in Scalate makes me leery of using
it. Terence Parr's paper, "Enforcing Strict Model-View Separation in Template
Engines" (http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf) pretty much
sums it up for me.

Steven Shaw
Joined: 2009-02-01,
User offline. Last seen 2 years 39 weeks ago.
Re: Scala and templates?
On 6 April 2010 02:24, Brian Clapper <bmc@clapper.org> wrote:
The ability to insert arbitrary Scala code in Scalate makes me leery of using it. Terence Parr's paper, "Enforcing Strict Model-View Separation in Template
Engines" (http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf) pretty much
sums it up for me.

I really liked that paper too. I've used Velocity in the past and appreciated the fact that it's good to be able to prevent "too much" from going on. I do recall that even in the paper on StringTemplate, Terence remarks something about writing a functional language and avoiding side-effects. It's seems to me that the problems with embedded code within templates are mostly related to side effects. i.e. prevents "too much" from going on is almost always just trying to prevent side effects. There you could argue that as long - as long as you stay pure - that using something like Scalate (or indeed embedded XHTML directly in your Scala code) is just fine and dandy even according to Terence Parr. I don't know anything about it but some kind of "effects system" for Scala would be terrific - where you could say "look scalac, do not allow any side effects here in my template, thanks!".
One other useful feature for a template language these days is in the context of web (ajax <sigh>) applications. It would be nice to be able to use your templates on the client-side in addition to the server-side. This allows you to change your mind about where stuff is rendered without having to convert from one template language to another. Of course, it won't be seamless in any case but it will be much easier. Also, your web designers will only have one markup/template language to get used to. If Scala were to target JS/Browser as a platform then this issue could be resolved without using JS (or something that compiles to JS) on the server side. Be good to see a Scala GWT or some kind of Scala -> JS compiler. If you don't have such a compiler you end up with a template language with a limited set of features (something like Google's Closure Templates http://code.google.com/closure/templates/) or using JS-based templates and having to use JS on the server side - in addition to your favourite language - Scala, of course ;).
If I had a vote, I'd vote that JS becomes a target platform alongside JVM and CLI. I'd love to help to make that happen if I was able. Anyone know the status of projects like GWT with respect to Scala->JS?
Cheers,Steve.
James.Strachan
Joined: 2009-07-08,
User offline. Last seen 2 years 25 weeks ago.
Re: Scala and templates?

On 6 April 2010 04:51, Steven Shaw wrote:
> Be good to
> see a Scala GWT or some kind of Scala -> JS compiler. If you don't have such
> a compiler you end up with a template language with a limited set of
> features (something like Google's Closure
> Templates http://code.google.com/closure/templates/) or using JS-based
> templates and having to use JS on the server side - in addition to your
> favourite language - Scala, of course ;).
> If I had a vote, I'd vote that JS becomes a target platform alongside JVM
> and CLI. I'd love to help to make that happen if I was able. Anyone know the
> status of projects like GWT with respect to Scala->JS?

I'd love that too; having to go back to using Java to work on GWT
makes me feel dirty :)

This was the last I heard: http://scalagwt.gogoego.com/

until Martin mentioned this
http://old.nabble.com/Re%3A--scala-announce--Re%3A--scala--Your-Summer-o...

my fingers and toes are still crossed (making typing quite difficult :)

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland