美文网首页
二 iOS模版引擎--Stencil

二 iOS模版引擎--Stencil

作者: 搞好关系 | 来源:发表于2019-01-18 17:24 被阅读3次
image.png
GitHub链接
简略语法:
There are {{ articles.count }} articles.

<ul>
  {% for article in articles %}
    <li>{{ article.title }} by {{ article.author }}</li>
  {% endfor %}
</ul>
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)

简单使用


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

调用

 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];
    }

相关文章

网友评论

      本文标题:二 iOS模版引擎--Stencil

      本文链接:https://www.haomeiwen.com/subject/lfondqtx.html