Giter Site home page Giter Site logo

dejs's Introduction

dejs

Build Status

Features

Supported

  • <%= %> Output escaped value
  • <%- %> Output raw value
  • <%# %> Comment (nothing will be shown)
  • <% %> Evaluate (use control flow like: if, for)
  • include partial ejs template

Not supported

  • All other features of ejs

Usage

import * as dejs from "https://deno.land/x/[email protected]/mod.ts";
  • renderFile (filePath: string, params: Params): Promise<Deno.Reader>
    • renders from file, outputs Deno.Reader
  • render (body: string, params: Params): Promise<Deno.Reader>
    • renders from string, outputs Deno.Reader
  • renderFileToString (filePath: string, params: Params): Promise<string>
    • renders from file, outputs string
  • renderToString (body: string, params: Params): Promise<string>
    • renders from string, outputs string
  • compile (reader: Reader): Promise<Template>
    • only compiles ejs and returns Template(params: Params): string
    • use this to cache compiled result of ejs

Render from file

  • template.ejs
<body>
  <% if (name) { %>
    <h1>hello, <%= name %>!</h1>
  <% } %>
</body>
  • index.ts
const { cwd, stdout, copy } = Deno;
import { renderFile } from "https://deno.land/x/dejs/mod.ts";

const output = await renderFile(`${cwd()}/template.ejs`, {
  name: "world",
});
await copy(output, stdout);
  • console
$ deno index.ts
<body>

    <h1>hello, world!</h1>

</body>

Render from string

const { cwd, stdout, copy } = Deno;
import { render } from "https://deno.land/x/dejs/mod.ts";

const template = `<body>
  <% if (name) { %>
    <h1>hello, <%= name %>!</h1>
  <% } %>
</body>`;

const output = await render(template, {
  name: "world",
});
await copy(output, stdout);

Include partial ejs template

  • To include template from other file, use include function in ejs.
  • include resolves views from relative path from executed ts / js file. (not from ejs template file).
    • This behavior may change in the future.

Usage

await include(filePath, params)

Example

  • views/header.ejs
<html>
<head>
  <title><%- title %></title>
</head>
<body>
  • views/footer.ejs
</body>
</html>
  • views/main.ejs
<%- await include('views/header.ejs', { title: 'include example' }) %>
<h1>hello, world!</h1>
<%- await include('views/footer.ejs') %>
  • index.ts
const { cwd, stdout, copy } = Deno;
import { renderFile } from "https://deno.land/x/dejs/mod.ts";

const output = await renderFile(`${cwd()}/views/main.ejs`);
await copy(output, stdout);
  • console
$ deno index.ts
<html>
<head>
  <title>include example</title>
</head>
<body>
<h1>hello, world!</h1>
</body>
</html>

Limitations

  • backslashes at line end will removed.

Development

Update modules

  • Please use dem
dem update https://deno.land/[email protected]

Lint

  • make lint

Format

  • make fmt

Testing

  • make test

Author

syumai

License

MIT

dejs's People

Contributors

eliassjogreen avatar irustm avatar leodog896 avatar lowlighter avatar marvinborner avatar michael-spengler avatar syumai avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

dejs's Issues

render and renderFile Not Working

Problem

Returned value of using the render and renderFile method always returns Buffer {} and not the markup content.

Expectation

Returns the markup with the data within populated

Steps to Reproduce

// index.ejs
<body>
  <% if (name) { %>
    <h1>hello, <%= name %>!</h1>
  <% } %>
</body>
// app.ts
import { renderFile } from "https://deno.land/x/dejs/mod.ts";
const tpl = await renderFile(`${Deno.cwd()}/index.ejs`, { name: 'world'});
console.log(tpl) // Buffer {}

Has the same result when using the render method. Can clarify that it is correctly reading the contents of the file

Module '"../../std/io/bufio"' has no exported member 'EOF'.

Error trace:

error TS2305: Module '"../../std/io/bufio"' has no exported member 'EOF'.

► https://deno.land/x/dejs/dejs.ts:4:21

4 import { BufReader, EOF } from 'https://deno.land/std/io/bufio.ts';

Environment:

❯❯❯ deno version
deno: 0.11.0
v8: 7.7.37
typescript: 3.5.1

Maybe pinning the std version could fix this? I see other modules like alosaur worked around this by only importing from [email protected]

DOUBT: dynamic render

Hi, I would like to know if there is a way to render dynamically on client side, I used abc as in the example: https://deno.land/x/abc/examples/template/

but I can't to use event handlers like onclick

// index.ejs
<%
  let color= "blue";
  function changeColor() { color= "green"; }
 %>
<button onclick=<%= changeColor() %>>Change p color</button>
<p style="color: <%= color %>"></p>

I know use Vanilla, I could have used document.getElementById("aaa").style.color= "yellow"; in a <script>, the question is about change variables dynamically on browsers. Because if not dynamic, I see no reason to use static ejs

thanks

Uncaught SyntaxError: missing ) after argument list on seemingly okay file

haii,
i receive an 'uncaught syntax error' when templating a seemingly okay file. here is a minimal example

// test.ts
import * as dejs from 'https://deno.land/x/[email protected]/mod.ts';

const readerToString = async (reader: Deno.Reader) =>
  new TextDecoder().decode(await Deno.readAll(reader));
const reader = await dejs.renderFile('./test.txt', { baz: 'baz' })
await readerToString(reader)
// test.txt
console.log(`foo bar ${baz}`);
deno run --allow-read test.ts
  • Error
error: Uncaught SyntaxError: missing ) after argument list
    at mod.ts:64:12
    at new Promise (<anonymous>)
    at mod.ts:48:11
    at Module.renderFile (mod.ts:168:10)
    at async test.ts:5:16

not sure what is going on here

renderFile cannot handles paths generated from import.meta.url

import { join } from "https://deno.land/std/path/mod.ts";
import { renderFile } from "https://deno.land/x/dejs/mod.ts";
const { stdout, copy } = Deno;

const output = await renderFile(join(import.meta.url, "../index.html"), {});
await copy(stdout, output);

output:

error: Uncaught NotFound: The system cannot find the path specified. (os error 3)
► $deno$/ops/dispatch_json.ts:43:11
    at NotFound ($deno$/errors.ts:75:5)
    at unwrapResponse ($deno$/ops/dispatch_json.ts:43:11)
    at sendAsync ($deno$/ops/dispatch_json.ts:98:10)

I think it is caused by the parameter carrying the "file:/" prefix. Is it as expected?

Using \n in script tag will result in actual line break sent to client

Hi.

I have overall positive experience with dejs, but found a rather interesting bug: when you use \n, it will result in line break being sent to the client (which can break scripts). I found this when trying to use newline in console log and it resulted in script having invalid syntax (as double quote strings cannot be multiline).

This can be fixed by escaping it again, but I think it shouldn't be needed to do only to support ejs.

Cannot catch undefined params, ReferenceError

deno: 1.9.0 and testet with 1.7.x

import * as dejs from "https://deno.land/x/[email protected]/mod.ts";

const tmpl = 'hello <%= name %>';

try {
  console.log(
    await dejs.renderToString(tmpl, {})
  );
} catch (e) {
  console.error(e)
}

console.log('done');
`````


Get this error
`````
error: Uncaught (in promise) ReferenceError: name is not defined
      f(...Object.values(args));
      ^
    at eval (eval at <anonymous> (https://deno.land/x/[email protected]/mod.ts:64:23), <anonymous>:4:59)
    at eval (eval at <anonymous> (https://deno.land/x/[email protected]/mod.ts:64:23), <anonymous>:6:9)
    at https://deno.land/x/[email protected]/mod.ts:82:7
    at new Promise (<anonymous>)
    at https://deno.land/x/[email protected]/mod.ts:69:11
    at Module.renderToString (https://deno.land/x/[email protected]/mod.ts:189:10)
`````




https://deno.land/x/[email protected]/mod.ts 404

curl https://deno.land/x/[email protected]/mod.ts -I
HTTP/1.1 200 Connection Established

HTTP/2 404
date: Thu, 12 Nov 2020 12:47:28 GMT
content-type: text/plain;charset=UTF-8
content-length: 13
set-cookie: __cfduid=dd5fa0a41d6ea41b07d88851a78602d8d1605185247; expires=Sat, 12-Dec-20 12:47:27 GMT; path=/; domain=.deno.land; HttpOnly; SameSite=Lax; Secure
access-control-allow-origin: *
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
report-to: {"endpoints":[{"url":"https://a.nel.cloudflare.com/report?s=CGm%2Bko%2FdQmFJH06j5rLewlgaWoGUjj7Xm%2Fj9Xtdq1yMNDgY0CEOeMnV5jvOFDFepbUbSBwiaQV%2F7aYWqfWoAi%2BViK6MmWZSMTmY%3D"}],"group":"cf-nel","max_age":604800}
nel: {"report_to":"cf-nel","max_age":604800}
server: cloudflare
cf-ray: 5f105c958de20ac0-NRT

Allow overwriting include

To allow for a more dynamic resolution of partial templates I suggest allowing overwriting the include function with a param named "include". This is currently not possible because of the order in which the args object is constructed.

I suggest swapping lines 71 and 72 to allow for this to be possible.

The current args object:

const args = {
    ...params,
    include,
    $$OUTPUT: output,
    $$FINISHED: resolve,
    $$ESCAPE: escape
};

The suggested args object:

const args = {
    include,
    ...params,
    $$OUTPUT: output,
    $$FINISHED: resolve,
    $$ESCAPE: escape
};

Type 'unique symbol' is not assignable to type 'number'

Hei,

I was checking out Dinatra and tried using dejs. It was working for me but after upgrading to most recent deno I see the errors below, similiar to the ones from the latest CI failure. Do you have a fix for this?

Cool project, thanks!

deno run --allow-read --allow-net src/main.ts
[0/1] Compiling file:///Users/scanf/src/github.com/scanf/uuid.alemayhu.com/src/main.tshttps://raw.githubuserconte
nt.com/syumai/dejs/master/dejs.ts:99:9 - error TS2469: The '<' operator cannot be applied to type 'symbol'.

99     if (byte < 0) {
           ~~~~
https://raw.githubusercontent.com/syumai/dejs/master/dejs.ts:103:14 - error TS2345: Argument of type 'number | un
ique symbol' is not assignable to parameter of type 'number'.
  Type 'unique symbol' is not assignable to type 'number'.

103     buf.push(byte);
                 ~~~~

make: *** [hello] Error 1
Alexanders-MacBook-Pro:uuid.alemayhu.com scanf$ make
deno run --allow-read --allow-net src/main.ts
[0/1] Compiling file:///Users/scanf/src/github.com/scanf/uuid.alemayhu.com/src/main.tshttps://raw.githubuserconte
nt.com/syumai/dejs/master/dejs.ts:99:9 - error TS2469: The '<' operator cannot be applied to type 'symbol'.

99     if (byte < 0) {
           ~~~~
https://raw.githubusercontent.com/syumai/dejs/master/dejs.ts:103:14 - error TS2345: Argument of type 'number | un
ique symbol' is not assignable to parameter of type 'number'.
  Type 'unique symbol' is not assignable to type 'number'.

103     buf.push(byte);

Use official repos

Could you please link to the official repository instead of your copied version in vendor? Then the deno cache for overlapping files could be used, its more up-to-date and it is even more trustworthy.

Add external dependencies to deps.ts and reference them from there within your local project. It makes it more clear which dependencies you use.

include() path resolution doesn't match documentation

The readme currently says,

include resolves views from relative path from executed ts / js file. (not from ejs template file).

This is either ambiguous phrasing or a mistake. Right now include calls renderFile, which calls Deno.open. Deno.open resolves paths relative to Deno.cwd(), not the template path or the executed file path. This means that changing the current directory though Deno.chdir breaks include.

[Fixed] SyntaxError: Unexpected identifier '$$OUTPUT' + SyntaxError: Unexpected token ')'`

Hi. I'm new to the whole deno ecosystem and wanted to port some npm packages to deno.

I decided to port https://github.com/cpiber/epub-gen-memory and came across your project.

I have been facing some issues along the way. I've never tried ejs before.

So i created a new branch of the project just for this issue which is at https://github.com/waptik/epubgen/tree/dejs-issue.

When i run deno task test, i get error: (in promise) SyntaxError: Unexpected token ')' as error and i think it's got to do with js statements that have ( & ) like an if(...) statement. Because when i comment https://github.com/waptik/epubgen/blob/dejs-issue/epub.ts#L173-#L201 and uncomment https://github.com/waptik/epubgen/blob/dejs-issue/epub.ts#L160-#L165 and i remove <navMap> ... </navMap> from toc.ncx.ejs(if i don't remove it, i get the error for this issue's title), the epub file is generated successfully.

Full logs

Warning deno task is unstable and may drastically change in the future
Task test deno test --unstable -A --allow-read --allow-write --allow-env --allow-run --allow-hrtime ./tests/mod.ts
Check file:///home/waptik/code/deno/epubgen/tests/mod.ts
running 1 test from ./tests/mod.ts
download.epub ...
------- output -------
{
template: {
path: "/home/waptik/code/deno/epubgen/templates/ejs",
ejs: { rmWhitespace: true }
}
}
Generating Template Files...
Downloading fonts...
No fonts to download
Downloading images...
Uncaught error from ./tests/mod.ts FAILED
download.epub ... cancelled (0ms)

ERRORS

./tests/mod.ts (uncaught error)
error: (in promise) SyntaxError: Unexpected token ')'
const f = new Function(...Object.keys(args), src);
^
at new Function ()
at https://deno.land/x/[email protected]/mod.ts:82:17
at new Promise ()
at https://deno.land/x/[email protected]/mod.ts:69:11
at renderFileToString (https://deno.land/x/[email protected]/mod.ts:202:10)
at async EPub.generateTemplateFiles (file:///home/waptik/code/deno/epubgen/epub.ts:174:19)
This error was not caught from a test and caused the test runner to fail on the referenced module.
It most likely originated from a dangling promise, event/timeout handler or top-level code.

FAILURES

./tests/mod.ts (uncaught error)

FAILED | 0 passed | 2 failed (311ms)

error: Test failed

Deno version: 1.25.0+c3e48cb
dejs Version: 0.10.3

Include not working dejs

Hello, guys I'm having problem in including ejs file

I included my controller

import { viewPath } from "../globe.ts";
import { renderFile } from "https://deno.land/x/dejs/mod.ts";
const { copy, stdout } = Deno;
const home = async () => {
  let home = await renderFile(`${viewPath}/home.ejs`, { vp: viewPath });
  //return await copy(home, stdout);
};

export { home };

in my app entry point

import { app, get, post } from "https://denopkg.com/syumai/dinatra/mod.ts";
import { home } from "./controllers/app.controllers.ts";

app(
  get("/", async () => await home()),
);

in my home.ejs

<%- await include(`partials/head.ejs`, {}); %>

the result in browser just returned Internal server error

dejs could not find css styles in directory

Basically I have simple blog made with just a couple .ejs files and some assets.
I want to render these .ejs pages with deno and do some interaction,
so I tried to load it using dejs functions like this:

import {RouterContext} from "https://deno.land/x/[email protected]/mod.ts";
import {renderFileToString, render, renderFile} from "https://deno.land/x/[email protected]/mod.ts";

export const index = async (ctx: RouterContext) => {
    const currUser = ctx.state.currentUser;
    ctx.response.body = await renderFile(
        `${Deno.cwd()}/views/index.ejs`, {
            currUser
        });
};

but all I got -- only bare html no assets, no css styles
It seems that I need to specify path to my assets (which is refferd in .ejs) folder, but sadly I couldn't figure out the way how to do this with dejs

So directory structure looks like

├── ...<other TS files>
├── users.ts
└── views
    ├── assets
    │  ├── bootstrap
    │  │  ├── ...
    │  ├── css
    │  │  └── ...
    │  ├── ...
    ├── ...<other .ejs files>
    └── index.ejs

Assets is refferd like this in index.ejs

<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.