如何遍历 stringtemplate 中的 java 列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18437005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:36:56  来源:igfitidea点击:

how do I iterate though a java list in stringtemplate?

javastringtemplate-4

提问by mrjayviper

I want to iterate through a hibernate query results inside stringtemplate. I've been looking for examples but I can't find anything.

我想遍历字符串模板中的休眠查询结果。我一直在寻找例子,但我找不到任何东西。

can you please help? thanks

你能帮忙吗?谢谢

采纳答案by Chuck Lowery

The syntax looks like

语法看起来像

<items :{ item | <item> }>

Putting it together in Java:

将它放在 Java 中:

List<String> teams = Arrays.asList("Cats", "Birds", "Turtles");
ST s = new ST( "<teams :{team | <team> }>");
s.add("teams", teams);
System.out.println(s.render());

In this example, I iterate over the List and print each team that is in the teamslist. The result that would be printed is:

在此示例中,我遍历列表并打印列表中的每个团队teams。将打印的结果是:

Cats Birds Turtles 

We can explore the syntax that makes this happen. Before we do, remember, that the default delimiters in StringTemplate are less than <and greater than >. Since we didn't specify a different delimiter <>will be what we use in our example.See more about delimiters

我们可以探索使这种情况发生的语法。在我们这样做之前,请记住,StringTemplate 中的默认分隔符小于<和大于>。由于我们没有指定不同的分隔符 <>,我们将在我们的示例中使用它。查看有关分隔符的更多信息

:{ }

This set of symbols, the colon :and the open and closed brace {}can be read as "for each". In the example template, the code reads, for each teamin teamsprint team. The left side of the vertical pipe |indicates the variable that will be created for each iteration. It will hold the current team from the list of teams. The print is composed of the <team>on the right side of the vertical pipe |and the left side of the closing brace }. Anything that is on the right side of the vertical pipe |and before the closing base }will be evaluated to be printed.

这组符号、冒号:和开闭大括号{}可以读作“for each”。在这个例子中模板的代码读取,对每个teamteams打印team。垂直管道的左侧|表示将为每次迭代创建的变量。它将从团队列表中保存当前团队。印刷品由<team>竖管右侧的|和闭合支架左侧的 组成}。垂直管道右侧|和关闭底座之前的任何内容都}将被评估为打印。

:{ current value | everything in here will be printed }

In order to build on the concept, let's use a more complex data structure.

为了建立在这个概念上,让我们使用一个更复杂的数据结构。

public class Player {
    private String name;
    private int age;

    public Person(String name, int age) { 
        this.name = name; 
        this.age = age; 
    }
    public int getAge() { return age; }
    public String getName() { return name; }
}

Now we can create a few players for our team:

现在我们可以为我们的团队创建一些球员:

Player[] players = new Player[] {
    new Player("Bill", 29),
    new Player("Steve", 30),
    new Player("Toby", 15)
};

String playerTemplate = "<players:{ player |<player.name> is <player.age> <\n>}>"
ST s = new ST( playerTemplate  );
s.add("players", Arrays.asList(players));
System.out.println(s.render());

Giving a result of

给出一个结果

Bill is 29
Steve is 30
Toby is 15

Couple of things to note. We didn't access the properties age and name directly. ST called the methods getAge and getName. ST doesn't look to the properties. Instead, it looks to find the access methods.

需要注意的几件事。我们没有直接访问属性 age 和 name。ST 调用了 getAge 和 getName 方法。ST 不看属性。相反,它寻找访问方法。

What if we just wanted to iterate over a list that contained another list. We can do that as well. First, let's build up our data structure and fill it with a couple of lists.

如果我们只想迭代包含另一个列表的列表怎么办。我们也可以这样做。首先,让我们建立我们的数据结构并用几个列表填充它。

List<List<String>> listOfLists = asList(
    asList("One", "Two", "Three"), 
    asList("Four", "Five"), 
    asList("Six", "Seven", "Eight", "Nine")
);

The template will look like the following.

模板将如下所示。

<list :{ items |<items :{ item |<item> }><\n>}>

Our template, in this case, will just be a combination. The outer shell will iterate over the list we will hand in.

在这种情况下,我们的模板只是一个组合。外壳将遍历我们将提交的列表。

 <list :{ items |  what we will print   }>

Then for each item, we will print out the items in its list.

然后对于每个项目,我们将打印出其列表中的项目。

<items :{ item |<item> }>

Once we put it all together

一旦我们把它们放在一起

String template = "<list :{ items |<items :{ item |<item> }><\n>}>";
ST st = new ST( template);
st.add("list", listOfLists);
System.out.println(st.render());

We get a result that looks like the following.

我们得到如下所示的结果。

One Two Three 
Four Five 
Six Seven Eight Nine 

Building on this concept a little more we can create a second data structure that contains a list of players. This will demonstrate how to iterate within iteration.

在这个概念的基础上,我们可以创建包含玩家列表的第二个数据结构。这将演示如何在迭代中进行迭代。

The first thing we will need is a data structure that contains a list. For this we can create a Team for our players to be a part.

我们首先需要的是一个包含列表的数据结构。为此,我们可以为我们的玩家创建一个团队。

public class Team {
    private List<Player> players;
    private String name;

    public Team (String name, List<Player> players) {
        this.players = players;
        this.name = name;
    }

    public List<Player> getPlayers() {
        return players;
    }

    public String getName() {
        return name;
    }
}

Notice that our team contains players. This composition will allow us to build up two iterations.

请注意,我们的团队包含玩家。这种组合将允许我们建立两次迭代。

Now that we have our data structure lets set everything together to make a couple of teams with some players.

现在我们有了我们的数据结构,让我们把所有东西放在一起,组成几个有一些球员的球队。

List<Team> teams = asList(
        new Team("Billings", asList(
                new Player("Bill", 29),
                new Player("Steve", 30),
                new Player("Toby", 15)
        )),
        new Team("Laurel", asList(
                new Player("Chad", 32),
                new Player("Chuck", 29),
                new Player("Will", 24),
                new Player("Ben", 26)
        ))
);

Now lets create a template and fill in a few details:

现在让我们创建一个模板并填写一些细节:

String simpleTeamTemplate = "<teams:{ team |<team.name> has <length(team.players)> players<\n>}>";

ST template = new ST( simpleTeamTemplate );
template.add("teams", teams);

System.out.println(template.render());

That will print out

那会打印出来

Billings has 3 players
Laurel has 4 players

Our simple template is just about the same as our first template from above. The only real difference is that we are using a built-in method provided by ST length(). See more on functions here

我们的简单模板与上面的第一个模板几乎相同。唯一真正的区别是我们使用的是 ST 提供的内置方法length()在此处查看有关功能的更多信息

Let's increase the complexity of the templates a little to add in our second iteration.

让我们稍微增加模板的复杂性以添加到我们的第二次迭代中。

First, we will create our playersTemplate. This is almost identical to our playerTemplatetemplate from above. The only difference is that we have our players coming from a team: team.players.

首先,我们将创建我们的playersTemplate. 这几乎与我们playerTemplate上面的模板相同。唯一的区别是我们的玩家来自team: team.players

String playersTemplate = "<team.players :{ player |<player.name> is <player.age><\n>}>";

Now we will construct a second template that contains the first. In this template we can iterate over teams and for each team we will print out the name, number of players length(team.players), and everything in the playersTemplate.

现在我们将构建包含第一个模板的第二个模板。在这个模板中,我们可以遍历团队并为每个团队,我们将打印出来的name,众多玩家length(team.players)在,一切playersTemplate

String teamTemplate = "<teams:{ team |<team.name> has <length(team.players)> players<\n>"+playersTemplate+"}>"; 

Now let's put that all together.

现在让我们把它们放在一起。

ST teamsTemplate = new ST( simpleTeamTemplate);
teamsTemplate.add("teams", teams);

System.out.println(teamsTemplate.render());

That will print for us the following.

这将为我们打印以下内容。

Billings has 3 players
Bill is 29
Steve is 30
Toby is 15
Laurel has 4 players
Chad is 32
Chuck is 29
Will is 24
Ben is 26

Now, you aren't really going to want to combine your templates in this way. Appending strings together to compose templates is rather silly. StringTemplate offers tools to make this combination of partial templates very easy. If you are curious about combining templates you can find out more here

现在,您不会真的想以这种方式组合您的模板。将字符串附加在一起来组成模板是相当愚蠢的。StringTemplate 提供的工具可以让这种部分模板的组合变得非常容易。如果您对组合模板感到好奇,可以在此处找到更多信息

回答by mrjayviper

%staffForOrg: {staff|
    <tr>
        <td><a href="#%staff.id%a" class="directory " id="%staff.id%1" onclick="javascript: window.location='StaffInfo.html?id=%staff.id%';">%staff.telephoneNumber%</a></td>

    </tr>
}%


this code works perfectly.

这段代码完美无缺。

staffForOrg is a list of my model. I used hibernate to retrieve the records.

StaffForOrg 是我的模型列表。我使用休眠来检索记录。