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();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值