Server Side Swift with Vapor - Part 20: Embedding | Ray Wenderlich

Learn how to take full advantage of Leaf and embed templates in other templates to reduce duplication.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/4493-server-side-swift-with-vapor/lessons/20

So when Im trying to use #set("content") im getting this error:

[ ERROR ] TemplateTagError(tag: "set", source: TemplateKit.TemplateSource(file: "/Volumes/Data/Projekty/Demo Projects/Vapor/TILapp/Resources/Views/index.leaf", line: 0, column: 1, range: Range(1..<15)), reason: "Missing body") (EngineServer.swift:153)

Anyone has an idea why ? :confused:

@deor have you provided anything to the tag? So it should look something like

#set(“content”) {
  ...
}

If you don’t have the curly braces I guess that might give you the error

@0xtim Thanks for a quick response. Yes I have provided code inside the tag. However I can now see that my curly bracket is on the next line
#set(“content”)
{
…
}

I didn’t think that would matter, but changing it, fixed the issue. Thanks!

1 Like

Leaf should probably be a bit smarter about that but glad it’s working!

Is there any way to allow page specific <script> tags? I thought I could just add a #get("script") to my base.leaf and then put a #set("script") { type section in the leaf page, but as soon as my script has a } in it the embedding just stops at the previous line…so I get corrupt javascript in the loaded page.

@gargoyle that sounds like a bug in Leaf - it should be able to handle that. Raise an issue on vapor/leaf on GitHub to track that.

Having said that, you shouldn’t really have inline JavaScript anywhere - it’s considered unsafe and if you set a CSP (Content Security Policy) inline JavaScript is blocked because it’s an easy way to steal cookies or run spoofing attacks. Extract the script out into a separate file and just include the script rather than having the script source in Leaf.

@0xtim Good suggestion, Tim. I implemented it as you suggested. Thanks.

1 Like

Hi,
How about not repeating the table code. You put the same table in user and index.
Since the table is not something that you put in base, how can you handle this embedding? Of course things can ged more complicated when you have a lot of similar pages with different parts.

Thanks.

You should be able to fine a table.leaf template that contains the common table code and just use #embed("table") to bring it in

Thanks, I don’t know way I considered embed to be … inheritance. I expected a include or something for this. Is clear now how it works.