前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >二 iOS模版引擎--Stencil

二 iOS模版引擎--Stencil

原创
作者头像
大话swift
修改2019-02-18 11:22:29
4060
修改2019-02-18 11:22:29
举报
文章被收录于专栏:大话swift大话swift
image.png
image.png

GitHub链接

简略语法:

代码语言:txt
复制
There are {{ articles.count }} articles.

<ul>
  {% for article in articles %}
    <li>{{ article.title }} by {{ article.author }}</li>
  {% endfor %}
</ul>
代码语言:txt
复制
import Stencil

struct Article {
  let title: String
  let author: String
}

let context = [
  "articles": [
    Article(title: "Migrating from OCUnit to XCTest", author: "Kyle Fuller"),
    Article(title: "Memory Management with ARC", author: "Kyle Fuller"),
  ]
]

let environment = Environment(loader: FileSystemLoader(paths: ["templates/"]))
let rendered = try environment.renderTemplate(name: "article_list.html", context: context)

print(rendered)

简单使用

代码语言:txt
复制
import UIKit
import Stencil
import PathKit
import WebKit
@objc
public class StencilEngine: NSObject {
    let environment:Environment
    let localBundle: Bundle
    @objc public      init( bundlePath: String) {
        localBundle = Bundle.init(path: bundlePath)!
         environment = Environment(loader: FileSystemLoader.init(bundle: [ self.localBundle, Bundle.main]))

    }
    
    @objc public func render(for webView: UIWebView,  templateFileName: String, bundle: Bundle , context:[String:Any]?)throws-> String{
        do{

        let html = try environment.renderTemplate(name: templateFileName, context: context)
                webView.loadHTMLString(html, baseURL: self.localBundle.bundleURL)
            return html
        }catch{
            throw error
        }
    }
    
    @objc public func render(forUiWebView webView: UIWebView,  templateFileName: String, bundle: Bundle , context:[String:Any]?)throws-> String{
        do{
            
            let html = try environment.renderTemplate(name: templateFileName, context: context)
            webView.loadHTMLString(html, baseURL: self.localBundle.bundleURL)
            return html
        }catch{
            
            throw error
        }
    }
    
    
}

调用

代码语言:txt
复制
 StencilEngine * engine = [[StencilEngine alloc] initWithBundlePath:_bundlePath];
    
    _html =       [engine renderFor:self.webView
                             templateFileName:self.templateFileName bundle:[[NSBundle alloc] initWithPath:_bundlePath] context:jsonObj error:&engineError];
    
    if (engineError) {
        [self showError:engineError];
    }

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档