Skip to content

Views ​

Jinatra can render EJS templates from routes. View rendering is provided by the Node and Bun adapters; the default template directory is views/.

Render a template ​

Create a template such as views/home.ejs:

ejs
<main>
  <h1><%= title %></h1>
  <p>Welcome, <%= name %>.</p>
</main>

Return view() from a route:

js
import { app, view } from 'jinatra'
import { serve } from 'jinatra/node'

app.get('/', () => view('home', {
  title: 'Jinatra',
  name: 'Ada',
}))

serve(app)

The .ejs suffix is optional, so view('home') resolves to views/home.ejs. Template names can include subdirectories, such as admin/dashboard.

Values passed in the second argument are available as EJS data. Use EJS's escaped output tag (<%= ... %>) for user-controlled values. Use unescaped output (<%- ... %>) only for HTML you trust.

Layouts ​

Pass a third argument to apply a layout:

js
app.get('/', () => view('home', { title: 'Jinatra' }, 'layout'))

views/layout.ejs receives the rendered page as body (and as content):

ejs
<!doctype html>
<html lang="en">
  <head><title><%= title %></title></head>
  <body><%- body %></body>
</html>

The page is rendered first, then inserted into the layout. Use <%- body %> so the page's already-rendered HTML is not escaped.

Configure the views directory ​

Pass a directory to the adapter:

js
serve(app, { views: './templates' })

Or set it on the application, which is useful when the same configuration is used by different adapters:

js
const app = new Jinatra({ views: './templates' })

An adapter-level views option takes precedence over the application's setting. The directory may also be an EJS-compatible renderer function or an object with a render() method.

Runtime support

view() needs a configured renderer. Node and Bun configure one automatically. A direct app.fetch() integration must provide executionContext.renderView if it needs to render views; Cloudflare Workers do not use the Node EJS renderer by default.

Released under the MIT License.