Hypertext :看看 HTML 格式问题交给 Swift 代码能否如你所愿

1,042 阅读1分钟
原文链接: github.com

Compose valid HTML in Swift any way you want to.

Usage

import Hypertext

title { "hello world." }.render()
// hello world.

head { title { "hello world." } }.render()
// hello world.

head { title { "hello world." } }.render(startingWithSpacesCount: 0)
// 
//   
//     hello world.
//   
// 

Requirements

  • Swift 3.0+

Full usage

  1. Rendering a tag

    div().render() 
    // 
  2. Rendering a tag with child text

    div { "hello world." }.render()
    // 
    hello world.
  3. Rendering a tag with a child tag

    div { img() }.render()
    // 
  4. Rendering a tag with multiple child tags

    div { [img(), img(), img()] }.render()
    // 
  5. Rendering a tag with attributes

    link(attributes: ["rel": "stylesheet", "type":"text/css", "href":"./style.css"]).render()
    // 
    
  6. Rendering unminified, with newlines and two-space indentation

    head { title { "hello world." } }.render(startingWithSpacesCount: 0)
    // 
    //   
    //     hello world.
    //   
    // 
    
  7. Rendering a tag in a novel way, any way you want to

    func createTitleTag(forPageNamed pageName: String) -> title {
     return title { "Hypertext - \(pageName)" }
    }
    
    head { createTitleTag(forPageNamed: "Documentation") }.render()
    // Hypertext - Documentation
    
  8. Rendering a custom tag

    public class myNewTag: tag {
     override public init(setChildren: (() -> Renderable?)) {
       super.init(setChildren: setChildren)
       name = "myNewTag"
       isSelfClosing = true
     }
    }
    
    myNewTag().render()
    // 
    
  9. Rendering a custom type by adopting the protocol Renderable

    extension MyType: Renderable {
     public func render() -> String {
    
     }
    
     public func render(startingWithSpacesCount: Int) -> String {
    
     }
    }