天天看點

Andorid Freemarker與template.js使用

1. Freemarker 官方網站

注:官網下載下傳的freemarker是無法直接應用到Android中的,如果要使用需要修改源碼

測試代碼下載下傳

1). 在assets檔案夾下建立main.tpl檔案, 其中${user}為動态替換的内容

<html>
<head>
    <title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>Our latest product:</p>
</body>
</html>
           

2). 導入freemarker.jar與openbeans.jar

compile files('libs/freemarker.jar')
    compile files('libs/openbeans.jar')
           

3). 将main.tpl檔案拷貝至項目的/data/data/package/file/目錄下,并更名為main.ftl

/**
     * 準備模闆
     * @throws IOException
     */
    private void prepareTemplate() throws IOException {
        // 擷取app目錄 data/data/package/file/
        String destPath = getFilesDir().getAbsolutePath();
        File dir = new File(destPath);

        // 判斷檔案夾是否存在
        if (!dir.exists()){
            dir.mkdir();
        }

        // 需要生成的.ftl模闆檔案名及路徑
        String tempFile = destPath + "/" + "main.ftl";
        if (!(new File(tempFile).exists())){
            // 擷取assets中.tpl模闆檔案
            InputStream is = getResources().getAssets().open("main.tpl");
            // 生成.ftl模闆檔案
            FileOutputStream fos = new FileOutputStream(tempFile);
            byte[] buffer = new byte[7168];
            int len;
            while ((len = is.read(buffer)) > 0){
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fos.close();
            is.close();
        }
    }
           

4). 根據main.ftl檔案生成對應的main.html網頁

/**
     * 生成網頁
     * @throws IOException
     * @throws TemplateException
     */
    private void genHTML() throws IOException, TemplateException {
        String destPath = getFilesDir().getAbsolutePath();
        FileWriter out = null;
        // 資料源
        Map<String, String> root = new HashMap<>();
        // 傳入字元串
        root.put("user", "mazaiting");
        Configuration cfg = new Configuration(new Version(2, 3, 25));
        // 設定編碼字元
        cfg.setDefaultEncoding("UTF-8");
        // 設定報錯提示
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        // 設定報錯提示
        cfg.setLogTemplateExceptions(true);
        out = new FileWriter(new File(destPath + "main.html"));
        // 設定.ftl模闆檔案路徑
        cfg.setDirectoryForTemplateLoading(new File(destPath));
        // 設定template加載的.ftl模闆檔案名稱
        Template temp = cfg.getTemplate("main.ftl");
        // 将資料源和模闆生成.html檔案
        temp.process(root, out);
        out.flush();
        out.close();
    }
           

5). 在WebView中加載網頁

WebView mWebView = (WebView) this.findViewById(R.id.webView);

        try {
            prepareTemplate();
            genHTML();

            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    String templateDir = getFilesDir().getAbsolutePath();
                    String url = "file://" + templateDir + "main.html";
                    mWebView.loadUrl(url);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

           

2. template.js 項目位址

1). 在assets檔案夾下引入template.js檔案

2). 編寫main.html檔案

<html lang="en">

<head>
    <title>Welcome!</title>
</head>
<body>
<script id="script1" type="text/html">
    <h1>Welcome <%=user%>!</h1>
</script>

<div id="contentTop"></div>
<p>Our latest product</p>
<script src="template.js"></script>
<script>
        <!--從java代碼中擷取到資料-->
        var data = JSON.parse(window.java.getString());
        var tpl = template(document.getElementById('script1').innerHTML);
        var html = tpl(data);
        document.getElementById('contentTop').innerHTML = html;
</script>
</body>
</html>
           

3). 對WebView進行設定

WebView mWebView = (WebView) this.findViewById(R.id.webView);

        // 設定webView允許JavaScript
        mWebView.getSettings().setJavaScriptEnabled(true);
        // 建立JSON對象
        final JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("user", "mazaiting");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // 設定JavaScript執行的方法
        mWebView.addJavascriptInterface(new Object(){
            @JavascriptInterface
            public String getString() {
                return jsonObject.toString();
            }
        }, "java");
        try {
            // 設定網頁
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    String url = "file:///android_asset/main.html";
                    mWebView.loadUrl(url);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }