2016-06-23 2 views
0

HTML 데이터를 생성하기 위해 속도 템플릿과 JSON 문자열 데이터를 직접 사용하는 방법이 필요합니다. 예를 들어 : 은 속도 템플릿과 JSON을 사용하여 HTML을 생성 하시겠습니까?

는 어떻게이

을 수행 할 수 있습니다 String mergedHtml = Velocity.someMethodToParseTemplate("VelocityTemplate.vm" ,String JsonString"); ? "someMethodToParseTemplate"코드를 제안하십시오.

답변

3

예를 들어 org.json library을 사용하여 JSON 문자열을 구문 분석 한 다음 구문 분석 결과에서 VelocityContext를 작성하면됩니다.

<html> 
    <body> 
    $name is $age years old and lives $address.streetAddress, ${address.city}. 
    <br/> 
    $name's friends: 
    <ul> 
    #foreach($friend in $friends) 
     <li>$friend.name, who is $friend.age years old</li> 
    #end 
    </ul> 
    </body> 
</html> 

당신은이 같은 JSON 문자열에 병합 할 수 있습니다 :

하자가 다음과 같은 템플릿이 있다고 당신이 어떤 루트 속성 아래 JSON 객체를 포장하려면

import java.io.IOException; 
import java.io.StringWriter; 
import java.io.Writer; 
import org.apache.velocity.VelocityContext; 
import org.apache.velocity.app.VelocityEngine; 
import org.json.JSONObject; 

public class JsonPublisher 
{ 
    protected VelocityEngine velocity; 

    public JsonPublisher() 
    { 
    // init velocity                                                
    // default resource loader is a file loader on the current directory                                   
    velocity = new VelocityEngine(); 
    velocity.init(); 
    } 

    public String publish(String templatePath, String jsonString) throws IOException 
    { 
    // translate json string to velocity context                                         
    // (we only need to convey the properties of the root object)                                    
    JSONObject jsonObj = new JSONObject(jsonString); 
    VelocityContext context = new VelocityContext(); 
    for(String key : jsonObj.keySet()) 
    { 
     context.put(key, jsonObj.get(key)); 
    } 

    Writer writer = new StringWriter(); 
    velocity.mergeTemplate(templatePath, "UTF-8", context, writer); 
    writer.flush(); 

    return writer.toString(); 
    } 

    public static void main(String args[]) 
    { 
    try 
    { 
     String str = "{ \"name\": \"Alice\", \"age\": 20, \"friends\": "+ 
     "[ { \"name\":\"Bob\", \"age\":21 }, { \"name\":\"Carol\", \"age\":19 } ], " + 
     "\"address\": { \"streetAddress\": \"100 Wall Street\", \"city\": \"New York\" } }"; 
     String result = new JsonPublisher().publish("template.vm", str); 
     System.out.println(result); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
    } 
} 

문맥, $json라고 가정 해 봅시다. 그러면 더 간단합니다.

.... 
JSONObject jsonObj = new JSONObject(jsonString); 
VelocityContext context = new VelocityContext(); 
context.put("json", jsonObj);   
.... 
+0

멋진 설명 답을 보내 주셔서 감사합니다. 쿼리가 있었으므로 JSON이 큰 경우 변환 속도가 느려 집니까? –

+0

JSON 크기가 큰 경우 메서드가 적절하지 않을 수 있지만 큰 볼륨이 브라우저에 업로드되지 않으므로 HTML이 적절하지 않을 수 있습니다. 그것은 당신이 * 큰 *이라고 부르는 것에 정말로 달려 있습니다. 특정 크기 이상에서는 스트림 처리 (라인 파싱 + 게시, à la * sed/awk *) 만 관련되어 있으며 매우 자주 작성하는 것이 가장 좋습니다. –

1

주 대상 html의 ctive가 브라우저에 표시되면 클라이언트 측 속도 렌더링 엔진과 json + 템플릿을 클라이언트에 별도로 사용하는 것이 좋습니다.

클라이언트가 브라우저 인 경우 브라우저에서 velocityjs을 사용할 수 있습니다. 본질적으로 그것은 var renderedHtml = velocityjs.render(htmlTemplate,jsonData)과 같은 것으로 나타납니다. 그런 다음 renderedHtml을 일부 dom 요소의 innerHtml으로 설정할 수 있습니다.

체크 내 another answer for more detailed steps

관련 문제