Skip to content

Feature: referencing variables from markdown pages (placeholder substitution) #395

Closed

Description

@julen

First of all, thanks for sharing and supporting Docusaurus! It's been pretty easy to get started.

I'm posting a feature request — I haven't found anything similar in the issue tracker so forgive me if it's been discussed before.

Motivation: sometimes docs need to reference information such as version numbers, URLs etc. and having them manually typed in the markdown pages is not ideal because this type of information often gets referenced multiple times.

Taking that into account, it would be great if Docusaurus supported passing variables into pages (from e.g. siteConfig). It already supports special Markdown markup via the <AUTOGENERATED_TABLE_OF_CONTENTS> marker, and it could potentially do something similar for variables.

For example, typing in<VAR:projectName> would get replaced with the value of siteConfig.projectName. Ideally this works in code blocks too (```).

Activity

  1. added
    feature
    on Feb 27, 2018
  2. JoelMarcey commented on Feb 27, 2018

    @JoelMarcey
    Contributor

    Interesting idea. We did something similar for nuclide.io using JS and referencing the package.json file. I think this is something that could definitely be implemented for some upcoming version of Docusaurus.

  3. added
    difficulty: advanced
    on Feb 28, 2018
  4. tibdex commented on May 1, 2018

    @tibdex

    That would be an awesome feature!

    Julen mentioned "version numbers, URLs, etc." but it would also be great to insert automatically computed markup from JSDoc for instance. Thus, if you decide to implement it, it would be nice to support the injection of Markdown (or HTML) markup and not only scalar values.

  5. gedeagas commented on May 26, 2018

    @gedeagas
    Contributor

    HI, @JoelMarcey I am planning to take this after finishing #694 but I think I will work with scalar values first. Is that okay?

  6. JoelMarcey commented on May 27, 2018

    @JoelMarcey
    Contributor

    @gedeagas Sounds great! I think this is a feature that can be done in increments.

  7. zenflow commented on May 27, 2018

    @zenflow
    Contributor

    Isn't this another thing best left to markdown plugins?

  8. endiliey commented on May 27, 2018

    @endiliey
    Contributor

    While I agree with @zenflow, if @gedeagas intends to build his own plugin, that's welcome too☺

  9. gedeagas commented on May 27, 2018

    @gedeagas
    Contributor

    Hi @zenflow @endiliey, I am planning to do just that 😄 .
    Making a plugin for remarkable to support this on docusaurus 📦

  10. zenflow commented on May 27, 2018

    @zenflow
    Contributor

    Ok, but just to be clear: that plugin will not be included as a dependency of Docusaurus, right? It would be configured by users in their siteConfig.markdownPlugins?

    I'm just a bit confused by the fact that this is a feature request for Docusaurus when nothing actually needs to change in Docusaurus for this to be supported

  11. tibdex commented on May 31, 2018

    @tibdex

    Here's how variable injection can be done:

    Put this in siteConfig.js:

    const {Plugin: Embed} = require('remarkable-embed');
    
    // Our custom remarkable plugin factory.
    const createVariableInjectionPlugin = variables => {
      // `let` binding used to initialize the `Embed` plugin only once for efficiency.
      // See `if` statement below.
      let initializedPlugin;
    
      const embed = new Embed();
      embed.register({
        // Call the render method to process the corresponding variable with
        // the passed Remarkable instance.
        // -> the Markdown markup in the variable will be converted to HTML.
        inject: key => initializedPlugin.render(variables[key])
      });
    
      return (md, options) => {
        if (!initializedPlugin) {
          initializedPlugin = {
            render: md.render.bind(md),
            hook: embed.hook(md, options)
          };
        }
    
        return initializedPlugin.hook;
      };
    };
    
    const siteVariables = {
      scalar: 'https://example.com',
      // Since the variables are processed by Docusaurus's Markdown converter,
      // this will become a nice syntax-highlighted code block.
      markdown: [
        '```javascript',
        'const highlighted = true;',
        '```',
      ].join('\n'),
      // We can use HTML directly too as HTML is valid Markdown.
      html: [
        '<details>',
        '  <summary>More details</summary>',
        '  <pre>Some details</pre>',
        '</details>'
      ].join('\n')
    };
    
    const siteConfig = {
      markdownPlugins: [
        createVariableInjectionPlugin(siteVariables)
      ],
    
      // rest of the config
    };
    
    module.exports = siteConfig;

    Then, in one of the doc page, write:

    ## Scalar injection
    {@inject: scalar}
    
    ## Markdown injection
    {@inject: markdown}
    
    ## HTML injection
    {@inject: html}

    And this is what Docusaurus would render:

    screenshot-2018-5-30 variable injection demo test site

    As you can see, by leveraging remarkable-embed, the implementation of the custom plugin for variable injection is quite small. I'm not even sure it's worth making a dedicated npm package out of it.

    The only drawback I can see is that the injected markup isn't pre-processed by Docusaurus. For instance, if one of the variables contains a Markdown title such as ## Custom title, this title won't appear in the secondary on-page navigation.

  12. gedeagas commented on Jun 2, 2018

    @gedeagas
    Contributor

    Awesome @tibdex.
    I guess my comment above is obsolete 😄

  13. cmdcolin commented on Aug 8, 2018

    @cmdcolin
    Contributor

    This is really sweet tibdex...it is not replacing variables that are inside of a markdown code block though. I guess those are kind of regarded as literals but as I might want some code to depend on a variable, is there anything I should do?

    Edit: also realized the original post requests having this feature available in code blocks

  14. endiliey commented on May 14, 2019

    @endiliey
    Contributor

    This issue is closed due to stale activity.

    If you think there is a need for it, please open up a new issue with new template.

  15. 44 remaining items

  16. alexandernst commented on Apr 4, 2023

    @alexandernst
    Contributor

    In case you want to make it work for links:

    const visit = require('unist-util-visit');
    
    const plugin = (options) => {
      const transformer = async (ast) => {
        visit(ast, ['text', 'code', 'link'], (node) => {
          // Replace all occurrences of VAR::varName with the value of varName
          let value;
          switch (node.type) {
            case "link":
              value = node.url;
              break;
    
            case "text":
            case "code":
              value = node.value;
              break;
          }
          value = value.replace(/VAR::([A-Z_]+)/ig, (match, varName) => {
            return options.replacements[varName] || match;
          });
    
          switch (node.type) {
            case "link":
              node.url = value;
              break;
    
            case "text":
            case "code":
              node.value = value;
              break;
          }
        });
      };
      return transformer;
    };
    
    module.exports = plugin;

    Note that you must install "unist-util-visit": "2.0.3" for any of this to work. Later versions require ESM, which is not available "here".

  17. changed the title [-]Feature: referencing variables from markdown pages[/-] [+]Feature: referencing variables from markdown pages (placeholder substitution)[/+] on Apr 7, 2023
  18. added a commit that references this issue on Jul 26, 2023
  19. alexfornuto commented on Sep 18, 2023

    @alexfornuto

    Many thanks to @Zenahr and @alexandernst for the plugin! In testing the latest version posted I found that it doesn't work for inline code snippets. How difficult would it be to expand the plugin to cover this use case?

  20. slorber commented on Sep 19, 2023

    @slorber
    Collaborator

    Many thanks to @Zenahr and @alexandernst for the plugin! In testing the latest version posted I found that it doesn't work for inline code snippets. How difficult would it be to expand the plugin to cover this use case?

    Just adding support for AST node type inlineCode in addition to the already supported code type.

  21. ZenaMel commented on Sep 20, 2023

    @ZenaMel
    Contributor

    Many thanks to @Zenahr and @alexandernst for the plugin! In testing the latest version posted I found that it doesn't work for inline code snippets. How difficult would it be to expand the plugin to cover this use case?

    @alexfornuto see below.

    const visit = require('unist-util-visit');
    
    const plugin = (options) => {
      const transformer = async (ast) => {
        visit(ast, ['text', 'code', 'link'], (node) => {
          // Replace all occurrences of VAR::varName with the value of varName
          let value;
          switch (node.type) {
            case "link":
              value = node.url;
              break;
    
            case "text":
            case "code":
              value = node.value;
              break;
          }
          value = value.replace(/VAR::([A-Z_]+)/ig, (match, varName) => {
            return options.replacements[varName] || match;
          });
    
          switch (node.type) {
            case "link":
              node.url = value;
              break;
    
            case "text":
            case "code":
              node.value = value;
              break;
    
            case "inlineCode": // <-- THIS HANDLES INLINE CODE BLOCKS.
              node.value = value;
              break;
          }
        });
      };
      return transformer;
    };
    
    module.exports = plugin;
  22. slorber commented on Sep 20, 2023

    @slorber
    Collaborator

    @Zenahr you probably also need to visit inlineCode nodes no? And also add it to the first switch? Didn't try but this would look better to me:

    const visit = require(https://github.com/syntax-tree/unist-util-visit);
    
    const plugin = (options) => {
      const transformer = async (ast) => {
        visit(ast, ['text', 'code', 'inlineCode', 'link'], (node) => {
          // Replace all occurrences of VAR::varName with the value of varName
          let value;
          switch (node.type) {
            case "link":
              value = node.url;
              break;
    
            case "text":
            case "code":
            case "inlineCode":
              value = node.value;
              break;
          }
          value = value.replace(/VAR::([A-Z_]+)/ig, (match, varName) => {
            return options.replacements[varName] || match;
          });
    
          switch (node.type) {
            case "link":
              node.url = value;
              break;
    
            case "text":
            case "code":
            case "inlineCode":
              node.value = value;
              break;
          }
        });
      };
      return transformer;
    };
    
    module.exports = plugin;
  23. alexfornuto commented on Sep 20, 2023

    @alexfornuto

    Thanks, gents! I used @slorber's version FTW. This is my derp, as I tried doing the same thing but with pre instead of inlineCode.

  24. de-abreu commented on Aug 20, 2024

    @de-abreu

    Evening, @slorber. I'm not familiar with Javascript and would like to know how I could install your plugin.

  25. lunny commented on Sep 1, 2024

    @lunny

    Sorry to disturb everyone here. I found a workaround after a long time searching. And it's not mentioned in the above comments. Maybe useful for somebody. The documentation is https://docusaurus.io/docs/api/docusaurus-config#preprocessor

    Here is an example of how to use it. https://gitea.com/gitea/docs/src/branch/main/docusaurus.config.js#L213 . This will replace all @variable@ into the value whether it's in a code block or not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    difficulty: advancedfeature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions