2022-10-31

VLANG-VWEB Create a Template File with VIM

Vlang has a module dedicated to the development of web applications. A simple web server with a single endpoint (localhost) can be obtained with the following source code:

    // filename: vimweb.v
    import vweb
    import time

    struct App {
        vweb.Context
    }

    fn main() {
        vweb.run(&App{}, 5000)
    }


    ['/']
    pub fn (mut app App) home() vweb.Result {
        tnow := time.now()
        return $vweb.html()
    }

The decorator ['/'] defines the endpoint of the application while the function name home indicates as the HTML template the (server side) file ./templates/home.html. Then $vweb.html() compiles and embeds this HTML template into the application.

The option watch will re-compile the application each time the VLANG source code has changed:

   v.exe watch run vweb.v

but unfortunately, it will not re-compile the application when the HTML template has been modified. To automate this step I have created a local .vimrc as follows:

    augroup vweb
        autocmd bufwritepost *.html execute ':! rename.exe ".txt." "." templates/*.html && sed -i "" vimweb.v'
    augroup end

The video below shows the possibility to create an HTML template directly from VIM by using the command :TOhtml. Saving the resulting HTML file will also recompile the web application.