Skip to content

Commit

Permalink
feat: add support to hook into edge renderer instance
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Sep 5, 2022
1 parent bd00b98 commit 2de6d6a
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/Contracts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,12 @@ export interface EdgeContract {
*/
unmount(diskName: string): this

/**
* Get access to the underlying template renderer. Each render call
* to edge results in creating an isolated renderer instance.
*/
onRender(callback: (renderer: EdgeRendererContract) => void): this

/**
* Get a renderer instance to render templates
*/
Expand Down
25 changes: 24 additions & 1 deletion src/Edge/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ export class Edge implements EdgeContract {
options?: any
}[] = []

/**
* Array of registered renderer hooks
*/
private renderCallbacks: ((renderer: EdgeRendererContract) => void)[] = []

/**
* Reference to the registered processor handlers
*/
Expand Down Expand Up @@ -233,13 +238,31 @@ export class Edge implements EdgeContract {
return this
}

/**
* Get access to the underlying template renderer. Each render call
* to edge results in creating an isolated renderer instance.
*/
public onRender(callback: (renderer: EdgeRendererContract) => void): this {
this.renderCallbacks.push(callback)
return this
}

/**
* Returns a new instance of edge. The instance
* can be used to define locals.
*/
public getRenderer(): EdgeRendererContract {
this.executePlugins()
return new EdgeRenderer(this.compiler, this.asyncCompiler, this.GLOBALS, this.processor)

const renderer = new EdgeRenderer(
this.compiler,
this.asyncCompiler,
this.GLOBALS,
this.processor
)

this.renderCallbacks.forEach((callback) => callback(renderer))
return renderer
}

/**
Expand Down
17 changes: 17 additions & 0 deletions test/edge.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,23 @@ test.group('Edge', (group) => {
assert.equal((await edge.render('hello::foo', { username: 'virk' })).trim(), 'Hello virk')
assert.equal((await edge.render('hello::foo', { username: 'virk' })).trim(), 'Hello virk')
})

test('hook into renderer instance', async (assert) => {
const edge = new Edge()

edge.onRender((renderer) => {
renderer.share({ foo: 'bar' })
})

edge.mount('hello', fs.basePath)
edge.registerTemplate('hello::foo', {
template: 'Hello {{ foo }}',
})

assert.equal((await edge.render('hello::foo')).trim(), 'Hello bar')
assert.equal((await edge.render('hello::foo')).trim(), 'Hello bar')
assert.equal((await edge.render('hello::foo')).trim(), 'Hello bar')
})
})

test.group('Edge | regression', () => {
Expand Down

0 comments on commit 2de6d6a

Please sign in to comment.