Swift Vapor Leaf deliver html in a variable

你。 提交于 2019-12-23 14:13:34

问题


I need to create a complex html-table inside a Swift Vapor App.

Problem is: Leaf doesn't seem to support counting up variables like #(somevar += 1) nor concatenating string variables like #(somevar1 + somevar2)

So I decided to create my complex table inside the App and transfer it to the html template inside a variable. (in php I'm used to doing this all the time)

In the template I'd call the variable like

#(table) 

but turns out, I'm getting the plain html code as leaf escapes all variables.

But there is the #raw() function to print out plain html as such.

So I do

<!DOCTYPE html>
<html lang="de">
<head><title>Server</title></head>
<body>
<..>

<form action="parameters" method="post">

// here is the thing: leaf gets a html table within the string 'table'.
// If I do it like that lead doesn't recognize #(table) as a leaf variable.
#raw( #(table) )

<button type="submit">Save</button>
</form>


</body>
</html>

only to find out that #raw() does not look for variables but just prints out unescaped what is between the {}. So I still get in the website "#(table)" instead of my complex html-table.

So now I'm stuck. How do I get App-generated html code into the template as html?

Probably I am doing this all wrong. How do I get html code inside a leaf template at all? Or do I have to send the whole page then myself, as a http stream with a header…?

Thanks in advance, Tom


回答1:


Update

Since Vapor 3 the #raw(<var>) tag was not embedded by default in --template=web when creating your Vapor Leaf project. I had to register it manually in my configure.swift file :

/// Leaf add tags
services.register { container -> LeafTagConfig in
    var config = LeafTagConfig.default()
    config.use(Raw(), as: "raw")   // #raw(<myVar>) to print it as raw html in leaf vars
    return config
}

https://docs.vapor.codes/3.0/leaf/custom-tags/

Also if someone is seeking for the complete list of available tags, you can silmply search for TagRenderer in vapor dependencies, which is the protocol to conform if you want to create a custom tag :

Hope this can help




回答2:


Assuming you are not taking in user input to create this table, you should be able to use this:

#raw(table)

This does the same thing as #(table), but it doesn't escape the HTML, so it will properly render. Just make sure you are not making yourself vulnerable to XSS attacks if you do this.



来源:https://stackoverflow.com/questions/44524372/swift-vapor-leaf-deliver-html-in-a-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!