ykmnkmi / jinja.dart

Jinja2 template engine port for Dart.
https://pub.dev/packages/jinja
MIT License
51 stars 11 forks source link

Skip {{< and >}} syntax in rendering #9

Closed vaetas closed 3 years ago

vaetas commented 3 years ago

Hello,

I would like to use the following tags for other functionality:

However, this library throws the following error:

TemplateSyntaxError on line 1 column 12: primary expression expected

I see that I can configure variableStart and variableEnd. This only accepts strings and I'm not sure how to configure this so Jinja only parses tags like {{ abcd... }} and skips {{< abcd... >}} without throwing error.

Would you have an idea how I could accomplish this behavior?

Thanks!

ykmnkmi commented 3 years ago

Hello, if the option using variableStart: '{{{' & variableEnd: '}}}' is not suitable for variables, then you can override Environment.fromString for wrapping tags in {% raw %}...{{% endraw %}}:

import 'package:jinja/jinja.dart';

class NewEnvironment extends Environment {
  NewEnvironment({Loader? loader})
      : regExp = RegExp(r'({{<\s*/?\w+\s*>}})'),
        super(loader: loader);

  final RegExp regExp;

  @override
  Template fromString(String source, {String? path}) {
    source = source.replaceAllMapped(
        regExp, (match) => '{% raw %}${match[1]}{% endraw %}');
    return super.fromString(source, path: path);
  }
}

void main() {
  final env = NewEnvironment();
  final tmpl = env.fromString('{{< user >}}Hello {{ name }}!{{< /user >}}');
  print(tmpl.render(name: 'Jhon'));
}

Is this suitable?

vaetas commented 3 years ago

Thanks, this is perfect!

I've used the custom Environment and it seems to work correctly. Just for clarity, I've slightly edited this regexp to RegExp(r'({{<\s*\/?\w+\s*\/?>}})') so it also works with trailing slashes.

Thank you again for help.