Skip to main content
Deno 2 is finally here ๐ŸŽ‰๏ธ
Learn more

View Engine

A View Engine middleware for oka framework

Usage

remember to give --allow-read permission

> deno run --allow-net --allow-read <Your Program>

Denjucks/Nunjucks examples

Read more about Nunjucks language

  • Render ./index.html

<-- index.html -->
<body>
  hello {{ txt }}
</body>
// app.ts
import { Application } from "https://deno.land/x/oak/mod.ts";
import { viewEngine } from "https://raw.githubusercontent.com/gjuoun/oak-view-engine/master/mod.ts";

const app = new Application();

app.use(viewEngine());

app.use((ctx) => {
  ctx.render("index.html", { txt: "good day" });
});

await app.listen({ port: 8000 });
  • Render ./static/index.html

// app.ts
...

app.use(viewEngine({
  view_root: './static'
}))

app.use((ctx) => {
  ctx.render('index.html', { txt: "good day" })
});

...
  • Render by file name only(ignore file extension)

// app.ts
...

app.use(viewEngine({
  view_root: './static',
  view_ext: 'html'
}))

app.use((ctx) => {
  ctx.render('index', { txt: "good day" })
});

...
  • Use with ctx.state

<body>
  user : {{ctx.state.user.name}} <--John--> 
  hello {{ txt }} <--good day-->
</body>
// app.ts
...

app.use((ctx) => {
  ctx.state.user = {name: 'John'}
  ctx.render('index', { txt: "good day" })
});

...

Ejs Examples

Read more about Ejs syntax

<--./view/index.ejs-->
<body>
  Hobbies of <%=data.name%> are:<br />

  <ul>
    <% data.hobbies.forEach((item)=>{ %>
    <li><%=item%></li>
    <% }); %>
  </ul>
</body>
//app.js
...
app.use(
  viewEngine({
    view_root: "./view",
    view_engine: "ejs",
  })
);

app.use(async (ctx, next) => {
  const data = {
    name: "Akashdeep",
    hobbies: ["playing football", "playing chess", "cycling"],
  };
  ctx.render("index.ejs", { data });
});
...

Roadmap