views:

46

answers:

1

I store user editable articles in a database. Users can insert some simple widgets into the articles (graphs and so on). So far I've implemented this as a proof of concept by letting the user insert graphs like [graph-1] and than do a string search and replace.

I was wondering whether there are more efficient ways of calling templates from a string? Maybe involving Sitemesh?

+4  A: 

Here's a sample of code that takes a template and a binding Map with variables and renders it to a string:

import groovy.text.SimpleTemplateEngine

def engine = new SimpleTemplateEngine()
String templateContent = 'hello ${name}'
def binding = [name: 'world']

String rendered = engine.createTemplate(templateContent).make(binding).toString()

You would just need to replace the hard-coded 'templateContent' with a string from the database and populate the binding map with whatever data makes sense for that template.

Burt Beckwith
Burt's got it right, the only thing I'd add is that you likely want to escape or filter whatever it is that you're displaying to prevent script injection attacks using something like myString.encodeAsHTML().
Ted Naleid
Ah, that's clever! Injection attacks aren't much of a concern as the users in this case are highly trusted.
Kimble