CodeSampleX

Exemple

ejs 3.1.10: render template with data using ejs

Échantillon vérifié pour npm ejs 3.1.10: render template with data using ejs. Le contrat s'est exécuté sur node 22 · linux alpine/x64 · docker et a réussi.

sha256:a5683abf8ad574512f5e22d7d166bd01e445ef88bf38a43944a2c34b7e9cebe5

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-26

Cas

HOW
Objectif
render template with data using ejs
Paquets
Symboles
  • ejs.compile
  • ejs.render
Créé
2026-08-26T08:37:41Z

Contrat

  1. ejs.render interpolates data with HTML-escaped output using <%= %> tags
  2. ejs.render outputs raw unescaped HTML when using <%- %> tags
  3. ejs.render executes control flow scriptlets for conditional branching and iterations
  4. ejs.compile returns a reusable template function that renders with dynamic data
  5. ejs.render supports custom delimiters and open/close delimiter configurations
  6. ejs.compile with async option generates a template function that awaits asynchronous evaluations
  7. ejs.render allows overriding the default HTML escape function with a custom encoder
  8. ejs.render supports whitespace slurping with modifier tags to strip leading and trailing whitespace

Fichiers

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • test/contract.mjs

Télécharger l’artefact source (tar.gz)

Code source

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: render template with data using ejs
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/ejs@3.1.10
Demonstrate these symbols/APIs:
  - ejs.compile
  - ejs.render

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:39e13d2c771f85aa28df007b98488825b5702b452a674a32a6c0c0603f4edfd8","contract":["ejs.render interpolates data with HTML-escaped output using \u003c%= %\u003e tags","ejs.render outputs raw unescaped HTML when using \u003c%- %\u003e tags","ejs.render executes control flow scriptlets for conditional branching and iterations","ejs.compile returns a reusable template function that renders with dynamic data","ejs.render supports custom delimiters and open/close delimiter configurations","ejs.compile with async option generates a template function that awaits asynchronous evaluations","ejs.render allows overriding the default HTML escape function with a custom encoder","ejs.render supports whitespace slurping with modifier tags to strip leading and trailing whitespace"],"goal":"render template with data using ejs","kind":"HOW","packages":["pkg:npm/ejs@3.1.10"],"schemaVersion":1,"symbols":["ejs.compile","ejs.render"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/ejs@3.1.10"],"schemaVersion":1,"subject":"pkg:npm/ejs@3.1.10","symbols":["ejs.compile","ejs.render"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-ejs",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-ejs",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "ejs": "3.1.10"
      }
    },
    "node_modules/async": {
      "version": "3.2.6",
      "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",
      "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
      "license": "MIT"
    },
    "node_modules/balanced-match": {
      "version": "1.0.2",
      "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
      "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
      "license": "MIT"
    },
    "node_modules/brace-expansion": {
      "version": "2.1.4",
      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
      "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
      "license": "MIT",
      "dependencies": {
        "balanced-match": "^1.0.0"
      }
    },
    "node_modules/ejs": {
      "version": "3.1.10",
      "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz",
      "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==",
      "license": "Apache-2.0",
      "dependencies": {
        "jake": "^10.8.5"
      },
      "bin": {
        "ejs": "bin/cli.js"
      },
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/filelist": {
      "version": "1.0.6",
      "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz",
      "integrity": "sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA==",
      "license": "Apache-2.0",
      "dependencies": {
        "minimatch": "^5.0.1"
      }
    },
    "node_modules/jake": {
      "version": "10.9.4",
      "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz",
      "integrity": "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==",
      "license": "Apache-2.0",
      "dependencies": {
        "async": "^3.2.6",
        "filelist": "^1.0.4",
        "picocolors": "^1.1.1"
      },
      "bin": {
        "jake": "bin/cli.js"
      },
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/minimatch": {
      "version": "5.1.9",
      "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz",
      "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==",
      "license": "ISC",
      "dependencies": {
        "brace-expansion": "^2.0.1"
      },
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/picocolors": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
      "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
      "license": "ISC"
    }
  }
}
package.json
{
  "name": "sample-ejs",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "ejs": "3.1.10"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "render template with data using ejs",
  "kind": "HOW",
  "packages": [
    "pkg:npm/ejs@3.1.10"
  ],
  "symbols": [
    "ejs.compile",
    "ejs.render"
  ]
}
src/index.mjs
import ejs from 'ejs';

/**
 * Renders a template string with data and options.
 * @param {string} template - The EJS template string.
 * @param {object} [data={}] - Data object passed to the template.
 * @param {object} [options={}] - EJS configuration options.
 * @returns {string} Rendered template string.
 */
export function renderTemplate(template, data = {}, options = {}) {
  return ejs.render(template, data, options);
}

/**
 * Compiles a template string into a reusable rendering function.
 * @param {string} template - The EJS template string.
 * @param {object} [options={}] - EJS compilation options.
 * @returns {Function} Template render function accepting data.
 */
export function compileTemplate(template, options = {}) {
  return ejs.compile(template, options);
}

/**
 * Compiles and renders an asynchronous template function.
 * @param {string} template - The EJS template string with async operations.
 * @param {object} [data={}] - Data object passed to the template.
 * @param {object} [options={}] - EJS compilation options.
 * @returns {Promise<string>} Promise resolving to the rendered template.
 */
export async function renderAsyncTemplate(template, data = {}, options = {}) {
  const fn = ejs.compile(template, { ...options, async: true });
  return fn(data);
}

export { ejs };
export default ejs;
test/contract.mjs
import assert from 'node:assert/strict';
import ejs from 'ejs';
import { renderTemplate, compileTemplate, renderAsyncTemplate } from '../src/index.mjs';

// 1. ejs.render interpolates data with HTML-escaped output using <%= %> tags
{
  const template = '<p>Hello, <%= user %>! and <%= symbol %></p>';
  const data = { user: '<b>Alice</b>', symbol: 'x & y' };
  const rendered = ejs.render(template, data);
  assert.equal(rendered, '<p>Hello, &lt;b&gt;Alice&lt;/b&gt;! and x &amp; y</p>');

  // Helper renderTemplate verification
  const helperRendered = renderTemplate(template, data);
  assert.equal(helperRendered, rendered);
}

// 2. ejs.render outputs raw unescaped HTML when using <%- %> tags
{
  const template = '<div><%- rawHtml %></div>';
  const data = { rawHtml: '<span>unescaped content</span>' };
  const rendered = ejs.render(template, data);
  assert.equal(rendered, '<div><span>unescaped content</span></div>');
}

// 3. ejs.render executes control flow scriptlets for conditional branching and iterations
{
  const template = `<ul><% items.forEach((item, index) => { %><li><%= index + 1 %>: <%= item %></li><% }); %></ul>`;
  const data = { items: ['Alpha', 'Beta', 'Gamma'] };
  const rendered = ejs.render(template, data);
  assert.equal(rendered, '<ul><li>1: Alpha</li><li>2: Beta</li><li>3: Gamma</li></ul>');

  const conditionalTemplate = `<% if (isAdmin) { %>Admin View<% } else { %>User View<% } %>`;
  assert.equal(ejs.render(conditionalTemplate, { isAdmin: true }), 'Admin View');
  assert.equal(ejs.render(conditionalTemplate, { isAdmin: false }), 'User View');
}

// 4. ejs.compile returns a reusable template function that renders with dynamic data
{
  const template = 'Hello <%= name %> [ID: <%= id %>]';
  const compiled = ejs.compile(template);
  assert.equal(typeof compiled, 'function');

  assert.equal(compiled({ name: 'UserA', id: 101 }), 'Hello UserA [ID: 101]');
  assert.equal(compiled({ name: 'UserB', id: 102 }), 'Hello UserB [ID: 102]');

  // Helper compileTemplate verification
  const helperCompiled = compileTemplate(template);
  assert.equal(helperCompiled({ name: 'UserC', id: 103 }), 'Hello UserC [ID: 103]');
}

// 5. ejs.render supports custom delimiters and open/close delimiter configurations
{
  const customDelimTemplate = 'Welcome, <?= name ?>!';
  const customDelimRendered = ejs.render(customDelimTemplate, { name: 'Bob' }, { delimiter: '?' });
  assert.equal(customDelimRendered, 'Welcome, Bob!');

  const customBracketTemplate = 'Welcome, [%= name %]!';
  const customBracketRendered = ejs.render(
    customBracketTemplate,
    { name: 'Charlie' },
    { openDelimiter: '[', closeDelimiter: ']' }
  );
  assert.equal(customBracketRendered, 'Welcome, Charlie!');
}

// 6. ejs.compile with async option generates a template function that awaits asynchronous evaluations
{
  const asyncTemplate = 'Status: <% const res = await getStatus(); %><%= res %>';
  const compiledAsync = ejs.compile(asyncTemplate, { async: true });
  const result = await compiledAsync({
    getStatus: async () => 'active-service'
  });
  assert.equal(result, 'Status: active-service');

  // Helper renderAsyncTemplate verification
  const helperAsyncResult = await renderAsyncTemplate(asyncTemplate, {
    getStatus: async () => 'async-ready'
  });
  assert.equal(helperAsyncResult, 'Status: async-ready');
}

// 7. ejs.render allows overriding the default HTML escape function with a custom encoder
{
  const customEscape = (val) => String(val).toUpperCase();
  const template = 'Escaped: <%= value %>';
  const result = ejs.render(template, { value: 'lowercase_string' }, { escape: customEscape });
  assert.equal(result, 'Escaped: LOWERCASE_STRING');
}

// 8. ejs.render supports whitespace slurping with modifier tags to strip leading and trailing whitespace
{
  const template = '  <%_ const greeting = "hi"; _%>  <%= greeting %>  ';
  const result = ejs.render(template);
  assert.equal(result, 'hi  ');
}

console.log('Contract assertions completed successfully.');

Seeder d'origine

anonyme