Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a server-side template in Dart where I can set a different <title/> for each page?

Tags:

dart

First of all, I really like Dart and keep trying to use it in real projects, but then I hit problems like this one where every other web framework has an obvious solution but I can't figure out how to make it work in Dart.

The problem is I would like to render multiple pages using a single base template where I can set the title of the page on the server and then serve the page to the browser.

Something simple like this:

<!DOCTYPE html>
<html>
 <head>
  <title>{{ custom_title }}</title>
 </head>
 <body>
  {{ page_content }}
  <footer>Hey, Seth Ladd!</footer>
 </body>
</html>

Where I would then pass the template variables which would replace {{ custom_title }} and {{ page_content }} before being sent back to the browser. Does such a templating solution exist anywhere in the core dart libraries?

I've looked at the Web Components / Web UI stuff, but it appears that it's not possible to have components which live outside of the <body> tag. I could also alter this easily on the client side, but it's a little dirtier of a solution and raises some SEO concerns (since title is such an important indicator of page content).

like image 533
plowman Avatar asked Mar 26 '13 20:03

plowman


1 Answers

Try out mustache, a Dart implementation of mustache templates, a widely used templating syntax, with implementations in a number of languages.

Here's an example:

import 'package:mustache/mustache.dart';

main() {
    var source = '{{#names}}<div>{{lastname}}, {{firstname}}</div>{{/names}}';
    var template = new Template(source);
    var output = template.renderString({'names': [
        {'firstname': 'Greg', 'lastname': 'Lowe'},
        {'firstname': 'Bob', 'lastname': 'Johnson'}
    ]});
    print(output);
}

The Dart team is currently focused on client side development, so many basic server-side features are missing in the core libraries. However take a look at pub, there are a number of community maintained packages available.

Also see this similar package: mustache4dart.

like image 191
Greg Lowe Avatar answered Oct 13 '22 03:10

Greg Lowe