如何使StringTemplate V4忽略<作为分隔符? [英] How to get StringTemplate V4 to ignore < as delimiter?

查看:173
本文介绍了如何使StringTemplate V4忽略<作为分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用StringTemplate V4在我的项目中生成一些HTML代码. 我需要在模板中使用HTML格式,因此使用默认的定界符<>会很尴尬.

I'm using StringTemplate V4 to generate some HTML code in my project. I need to have HTML formatting in my templates, so using the default delimiters < and > would be very awkward.

因此,我正在创建一个将定界符作为参数传递的组(如此问题的建议),但这根本不起作用.

So, I'm creating a group passing the delimiter as argument (as recommended by this question), but it simply doesn't work.

这是我的测试代码:

public void testTemplate() {
    char sep = '$';
    STGroup stGroup = new STGroupString("temp",
            "<html>hello, $name$!</html>", sep, sep);
    System.out.println("Group created");
    ST st = stGroup.getInstanceOf("temp");
    if (st == null) {
        System.out.println("Failed to get template!");
    } else {
        st.add("name", "Guest");
        System.out.println("Template initialized correctly");
    }
}

这是我得到的输出:

temp 1:1: invalid character '<'
temp 1:5: invalid character '>'
temp 1:1: garbled template definition starting at 'html'
temp 1:6: garbled template definition starting at 'hello'
temp 1:13: invalid character '$'
temp 1:18: invalid character '$'
temp 1:19: invalid character '!'
temp 1:21: invalid character '<'
temp 1:22: invalid character '/'
temp 1:14: garbled template definition starting at 'name'
temp 1:26: invalid character '>'
temp 1:22: garbled template definition starting at 'html'
Failed to get template!

我在这里想念什么?

推荐答案

问题是提供给STGroupString构造函数的模板不是有效的组模板"语法.

The issue is the the template supplied to the STGroupString constructor is not valid "group template" syntax.

要获取不需要特殊语法的组模板,请尝试:

To get a Group Template that doesn't require the special syntax try:

STGroup group = new STGroup('$', '$');
group.registerRenderer(...);
CompiledST compiledTemplate = group.defineTemplate("name", ...);
compiledTemplate.hasFormalArgs = false; // very important!

// later on...
ST template = group.getInstanceOf("name");

(以上是我的C#代码的改编版,所以是YMMV.我试图确保类型/名称有效且语法正确,但尚未验证.请根据需要随时更新/更正.)

(This above is an adaptation of my C# code so YMMV. I have tried to ensure the types/names are valid and the syntax is correct, but have not verified it. Feel free to update/correct as required.)

快乐的编码.

这篇关于如何使StringTemplate V4忽略&lt;作为分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆