Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Vapor Leaf deliver html in a variable

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

like image 237
incredion Avatar asked Jun 13 '17 14:06

incredion


3 Answers

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 :

Available Tags

Hope this can help

like image 73
Olympiloutre Avatar answered Oct 17 '22 06:10

Olympiloutre


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.

like image 24
Caleb Kleveter Avatar answered Oct 17 '22 05:10

Caleb Kleveter


In vapor 4 it is:

#unsafeHTML(variable)

like image 30
Amr Avatar answered Oct 17 '22 07:10

Amr