2013-02-11 7 views
13

Mam mapę mieszania, jak poniżejFreemarker i hashmap. Jak mogę dostać klucz-wartość

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); 

My Freemarker szablon jest:

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

Celem jest wyświetlanie parę klucz-wartość w HTML, że” m generowanie. Proszę, pomóż mi to zrobić. Dzięki!

+1

Co jest wyświetlane? Gdzie jest błąd? – Aubin

Odpowiedz

33

Kod:

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 

Szablon:

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

wyjściowa:

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

Od wersji 2.3.25 jest lepszy sposób; zobacz: https://stackoverflow.com/a/38273478/606679 – ddekany

3

Użyj mapę, która zachowuje Kolejność wstawiania par klucz-wartość: LinkedHashMap

+0

Ta odpowiedź zakłada, że ​​problem polega na tym, że dane wyjściowe nie znajdują się w kolejności wstawiania. Nie jestem pewien, czy to prawda. – Gray

11

Od 2.3.25, można to zrobić:

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

Przed 2.3.25, w przypadku obiektów zawierających klucze, można spróbować użyć

<#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>