Подтвердить что ты не робот

Фримаркер и хэшмап. Как получить ключ-значение

У меня есть хэш-карта, как показано ниже.

HashMap<String, String> map = new HashMap<String, String>();
map.put("one", "1");
map.put("two", "2");
map.put("three", "3");

Map root = new HashMap();
root.put("hello", map);

Мой шаблон Freemarker:

<html><body>
    <#list hello?keys as key> 
        ${key} = ${hello[key]} 
    </#list> 
</body></html>

Цель состоит в том, чтобы отобразить пару ключевых значений в HTML, который я генерирую. Пожалуйста, помогите мне сделать это. Благодарю!

4b9b3361

Ответ 1

Код:

HashMap<String, String> test1 = new HashMap<String, String>();
Map root = new HashMap();
test1.put("one", "1");
test1.put("two", "2");
test1.put("three", "3");
root.put("hello", test1);


Configuration cfg = new Configuration(); // Create configuration
Template template = cfg.getTemplate("test.ftl"); // Filename of your template

StringWriter sw = new StringWriter(); // So you can use the output as String
template.process(root, sw); // process the template to output

System.out.println(sw); // eg. output your result

Шаблон:

<body>
<#list hello?keys as key> 
    ${key} = ${hello[key]} 
</#list> 
</body>

Вывод:

<body>
    two = 2 
    one = 1 
    three = 3 
</body>

Ответ 2

Начиная с версии 2.3.25, вы можете сделать это:

<body>
<#list hello as key, value> 
    ${key} = ${value} 
</#list> 
</body>

Ответ 3

Используйте карту, которая сохраняет порядок вставки пар ключ-значение: LinkedHashMap

Ответ 4

До 2.3.25 в случае ключей, содержащих объекты, вы можете попытаться использовать

<#assign key_list = map?keys/>
<#assign value_list = map?values/>
<#list key_list as key>
  ...
  <#assign seq_index = key_list?seq_index_of(key) />
  <#assign key_value = value_list[seq_index]/>
  ...
     //Use the ${key_value}
  ...
</#list>