www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to Add CSS and JS to vibe.d templates

reply seany <seany uni-bonn.de> writes:
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

Note that (as discussed in my previous post by Steven 
Schveighoffer) , there are some errors in the jade/pug template 
file. But even if we correct them, and then I try to use the 
setup, I do not get the styles. (Of course, i can't point my 
browser to www.my.server/main.css or so, because those endpoints 
are not defined. However, as I understood, all non-defined 
endpoints should anyway be redirected to public)

Thank you.
Jan 19 2023
parent Steven Schveighoffer <schveiguy gmail.com> writes:
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
Jan 19 2023