Search code examples
javascriptnode.jsnunjucksapostrophe-cms

How to render a custom view in a NPM module?


Since pushAsset does not allow to load external resources, I want to render this template/script of my NPM module:

views/tag.html

<script async src="https://www.googletagmanager.com/gtag/js?id={{ data.gid }}"></script>

NPM modules are kind of different to project level modules, because I cannot directly edit the project files.


Solution

  • Apostrophe provides helper functions for Nunjucks. Some of them – like addAfterContextMenu – can be used as hooks to insert templates of NPM modules into other templates.

    These hooks are declared inside apos.pages. Usage:

    self.apos.pages.startHead(function(req) {
      return self.partial('templateName', { gid: 'UA-123456-1' });
    });
    

    startHead could be a hook that inserts the partial inside the startHead block of outerLayoutBase. Currently, Apostrophe does not provide many hooks for NPM module authors. But this is subject to change.