11ty / eleventy

A simpler site generator. Transforms a directory of templates (of varying types) into HTML.
https://www.11ty.dev/
MIT License
16.86k stars 487 forks source link

Include inputPath in environment options passed to markdown #1510

Closed GeorgeNance closed 3 years ago

GeorgeNance commented 3 years ago

Is your feature request related to a problem? Please describe. Yes, It would be nice to have context to which file is being rendered when I am writing custom plugins for my markdown.

I am trying to process images that are in the same folder as a markdown file.

Describe the solution you'd like

Simply passing the inputPath to mdlib.render in Markdown.js

Describe alternatives you've considered There is no easy alternate at this point.

Additional context N/A

zachleat commented 3 years ago

Hmm—does page solve this? page.inputPath https://www.11ty.dev/docs/data-eleventy-supplied/#page-variable-contents

GeorgeNance commented 3 years ago

I don’t believe we are able to access page variables from plugins that are called when rendering . I may be wrong .

zachleat commented 3 years ago

This repository is now using lodash style issue management for enhancements. This means enhancement issues will now be closed instead of leaving them open.

View the enhancement backlog here. Don’t forget to upvote the top comment with 👍!

manunamz commented 2 years ago

For others who also want to access inputPath in a markdown-it plugin:

This is already possible, if a bit loopy. See details below.

function customPlugin (md, opts) {
  md.renderer.rules.custom_render_rule = function (tokens, index, opts, env) {
    // do some things...
    return `now you can access inputPath! ${env.page.inputPath}`
  }
}

However...

...you should keep in mind that by accessing env.page you are tying your plugin impelementation to 11ty. To make this more universally accessible, you might want to add a configuration such as:

const customPluginDefaults = {
  getAbsPathFromEnv: (env) => { return env.page.inputPath }, // in the case of 11ty
}

...which would change the render rule to look like:

function customPlugin (md, opts) {
  const fullOptions = { ...customPluginDefaults, ...opts }; // this line merges default options with custom options

  md.renderer.rules.custom_render_rule = function (tokens, index, opts, env) {
    // do some things...
    return `now you can access inputPath! ${fullOptions.getAbsPathFromEnv(env)}`
  }
}

EDIT:

A live example plugin can be viewed at: markdown-it-wikirefs; see its resolveHtmlHref option.

See it in action in eleventy-wikibonsai, which accesses the inputPath in its configuration.

nhoizey commented 1 year ago

And now there's also markdown-it-image-size thanks to @boyum: