the secret of Caddy's include template

dec 25 2021


as i've stated before, i really like Caddy. it's the webserver i use to host this website, and i think it's incredibly simple and easy to use. in this post, i'm going to explain how to use templates in Caddy to make your websites more modular.

to start using templates, you'll need to edit your Caddyfile. you can do this by simply adding the "templates" directive to it.

/etc/caddy/Caddyfile
example.com

templates
root * /var/www                
file_server

once you restart your Caddy server, it will be ready to process templates. while there are many templates available, the easiest to use, and most useful in my opinion, is the include template. the include template adds the content of one file into another seamlessly, making it perfect for frequently reused elements, like headers and footers. here is an example showing how they work.

foo.html (unprocessed)
<​!DOCTYPE html​>
<​html​>
  <​body​>
    <​p​>foo<​/p​>
    {​{include "bar.html"}​}
  <​/body​>
<​/html​>
bar.html
<​p​>bar<​/p​>
foo.html (processed)
<​!DOCTYPE html​>
<​html​>
  <​body​>
    <​p​>foo<​/p​>
    <​p​>bar<​/p​>
  <​/body​>
<​/html​>

while very simple, this trick allows you to save a lot of time dealing with duplicate code, by allowing you to make everything reference one file instead.