简体   繁体   English

使用StringTemplate生成条件代码

[英]Conditional code generation using StringTemplate

In my project, I have a class Device like this: 在我的项目中,我有一个类似Device类:

public class Device {
    private Set<String> abilities = new HashSet<String>();

    public Device(Set<String> abilities) {
        this.abilities = abilities;
    }

    public Set<String> getAbilities() {
        return abilities;
    }
}

I am initializing this Device class with: 我正在使用以下方法初始化此Device类:

Set<String> device1Abilities = new HashSet<String>();
device1Abilities.add("BadgeReader"); 
device1Abilities.add("TemperatureSensor");   
device1Abilities.add("xyz");
Device d1 = new Device(device1Abilities);

In my stringTemplateFile , I am retrieving abilities using 在我的stringTemplateFile ,我正在使用检索能力

$device.abilities :{ sc | abilities.add("$sc$"); }$

which will generates following code => 这将生成以下代码=>

abilities.add("BadgeReader");
abilities.add("TemperatureSensor");
abilities.add("xyz");

Now, my requirement is ----- I do not want to generate this line of code: 现在,我的要求是-----我不想生成以下代码行:

abilities.add("xyz");

What condition should I specify in 我应该在什么条件下指定

 $device.abilities :{ sc | abilities.add("$sc$"); }$

so that it does not generate that line? 这样它就不会产生那条线?

That computation really belongs in the model so you should do the filtering of the list that you passed to the template. 该计算实际上属于模型,因此您应该对传递给模板的列表进行过滤。 The template should not figure out which data to display. 模板不应弄清楚要显示哪些数据。 It should display the data that your model says it should display. 它应显示模型表示应显示的数据。 hope this helps. 希望这可以帮助。

See here . 这里 You are using an anonymous sub-template abilities.add("$sc$"); 您正在使用匿名子模板abilities.add("$sc$"); . Instead you can use a template call with sc as parameter. 相反,您可以使用带有sc作为参数的模板调用。 And there you can test on "xyz" . 在那里,您可以在"xyz"上进行测试。 Though maybe someone with more StringTemplate experience knows a shorter notation. 尽管也许有更多StringTemplate经验的人知道较短的表示法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM