How to Add CSS and JS to vibe.d templates

Steven Schveighoffer schveiguy at gmail.com
Fri Jan 20 05:42:25 UTC 2023


On 1/19/23 11:44 PM, seany wrote:
> Hi
> 
> Howcan one add CSS and JS to vibe.d templates? Here is my setup (vibe.d 
> project initiated with dub using dub init myproject vibe.d):
> 
> ./public:
> main.css  main.js
> 
> ./source:
> app.d
> 
> ./views:
> auth2fa.dt  fail.dt  login.dt  pair.dt  passfail.dt  userfail.dt
> 
> 
> I am trying to add a css file using `link(rel="stylesheet", 
> type="text/css", href="main.css")` in the diet templates, but it has no 
> effect. I took the files from here: 
> https://codepen.io/ricardoolivaalonso/pen/YzyaRPN

Keep in mind, this literally translates to a `link` tag in the HTML. So 
here is what happens:

1. your vibe project is running, and passes out the compiled template to 
the browser.
2. The browser sees the link tag, and attempts to ask the server for the 
file "main.css"
3. The vibe project tries to match that to its routes, and cannot find 
it, and so returns an error.

So this takes 2 steps to remedy:

1. Register a `serveStaticFiles` route with the glob `public/*`. See the 
docs here: https://vibed.org/api/vibe.http.fileserver/serveStaticFiles
2. Change your link to refer to `public/main.css`, instead of just 
`main.css`.

This is how it looks in my code:

```d
  router.get("/public/*", serveStaticFiles(""));
```

And the links look like:

```pug
link(rel="stylesheet",href="/public/css/flatpickr.min.css")
```

as an example. Note that I put my css files into a css subdirectory 
under public, and my javascript files under a js subdirectory. It all 
depends on how you want to set it up.

-Steve


More information about the Digitalmars-d-learn mailing list