Code Monkey home page Code Monkey logo

grunt-markdown's Introduction

grunt-markdown

Build Status

This grunt task takes a set of markdown files and converts them to HTML. It supports GFM with code highlighting. The code highlighting is done using highlight.js.

Getting Started

Install this grunt plugin next to your project's grunt.js gruntfile with:

npm install grunt-markdown --save-dev

Then add this line to your gruntfile:

grunt.loadNpmTasks('grunt-markdown');

Documentation

Creating a markdown task is simple. For the basic functionality add the following config in your gruntfile:

grunt.initConfig({
  markdown: {
    all: {
      files: [
        {
          expand: true,
          src: 'docs/src/*.md',
          dest: 'docs/html/',
          ext: '.html'
        }
      ]
    }
  }
});

Here is an example config using all of the options:

grunt.initConfig({
  markdown: {
    all: {
      files: [
        {
          expand: true,
          src: 'docs/src/*.md',
          dest: 'docs/html/',
          ext: '.html'
        }
      ],
      options: {
        template: 'myTemplate.jst',
        preCompile: function(src, context) {},
        postCompile: function(src, context) {},
        templateContext: {},
        contextBinder: false,
        contextBinderMark: '@@@',
        autoTemplate: true,
        autoTemplateFormat: 'jst',
        markdownOptions: {
          gfm: true,
          highlight: 'manual',
          codeLines: {
            before: '<span>',
            after: '</span>'
          }
        }
      }
    }
  }
});

These are the properties that the markdown task accepts:

  • files: This plugin supports use of the files API introduced in Grunt 0.4.0. Files may be specified using any one of the Compact Format, Files Objects Format, or Files Array Format (as in the above example).
  • options: options to be passed to the markdown parser
    • template: If you wish to specify your own html template, use the template option. Include the following line: <%=content%> where you want the compiled markdown inserted in your template
    • markdownOptions: Options passed directly to the markdown parser.
    • preCompile: is run before the markdown is compiled
    • postCompile: is run after the markdown has been compiled
    • templateContext: the default context for template expansion
    • contextBinder: this option is useful when we want to bind some parameters directly from markdown files. All data is stored in templateContext object.
    • contextBinderMark: with this option we can pass any marker between which we can grab your special parameters from markdown templates.
    • autoTemplate: if this option is set to true, script will search for template automatically. Template must be placed in this same catalog where markdown files are.
    • autoTemplateFormat: the template format when autoTemplate is true.

modifying content with preCompile and postCompile

Sometimes there is a need to modify the markdown content prior to compilation. This is most commonly used to augment the template context with meta data before expanding the html template.

preCompile

This function is run prior to the compilation of md to html. It has the following format:

  function(src, context) {
    //do stuff to src and context
    //optionally return the modified src
  }

postCompile

This function is run after the md has been converted to html. It has the following format:

  function(src, context) {
    //do stuff to src and context
    //optionally return the modified src
  }

templateContext

This object is used to expand your html template. Any data added to this object will be available in the template using the template syntax <%=myAttr%>.

This can also be a function which is expected to return a context object.

markdownOptions

Most markdown options are passed as-is to the marked markdown parser. The only option that is processed prior to compiling the markdown is the highlight option. If you specify 'auto' or 'manual' the task will handle highlighting code blocks for you using highlight.js. If you pass a custom function as the highlight option it will be used to highlight the code.

  • auto: Will try to detect the language
  • manual: will pass the language name from markdown to the highlight function
  • codeLines: specify text that should wrap code lines

contextBinder

Below you can see example how to use this option.

  markdown: {
    all: {
      files: [
        {
          expand: true,
          src: 'docs/src/*.md',
          dest: 'docs/html/',
          ext: '.html'
        }
      ],
      options: {
        template: 'myTemplate.jst',
        preCompile: function(src, context) {},
        postCompile: function(src, context) {},
        templateContext: {},
        contextBinder: true,
        contextBinderMark: '@@@',
        markdownOptions: {
          gfm: true,
          highlight: 'manual',
          codeLines: {
            before: '<span>',
            after: '</span>'
          }
        }
      }
    }
  }

Then inside markdown file we have to put: <!-- @@@key:value@@@ --> and it will be equal to:

templateContext: {
  key: 'value'
}

License

Copyright (c) 2012-2013 James Morrin Licensed under the MIT license.

grunt-markdown's People

Contributors

aurelioderosa avatar chriswren avatar ekonijn avatar isaachier avatar kuzmisin avatar maronmariusz avatar mattd avatar philips avatar taavit avatar thomaswelton avatar treasonx avatar vladikoff avatar willkan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

grunt-markdown's Issues

Suggestion on additional parameter to the `preCompile` and `postCompile` functions.

Hi.

It seems to me that there is a use case where the file (as in this.files element) that is being processed right now should be made available to the preCompile and postCompile functions.

The use case is as follows:

  • before processing the files, the metadata for all files is gathered (file names, folder structure) - in order to create some sort of documentation site, with relative paths and so on.
  • in order to create each individual HTML file from the template, it's context should have things like path or size (for example)

Unfortunately, there is no way of knowing, currently, which file is being processed.

I suggest a very simple change. Instead of passing src to the lib/markdown.js module, the entire file should be passed and then populated onto context.

templateContext.file = file;

Thoughts? :)

Also, latest changes are awesome.

Doesn't work with rename

{
            expand: true,
            src: './*.md',
            dest: './docs/',
            ext: '.html',
            rename: function (dest, src) {
              return dest.indexOf('README') === 0 ? './docs/index.html' : dest;
            }
}

And I get the error

Warning: Unable to read "./CONTRIBUTING.md,./README.md" file (Error code: ENOENT). Use --force to continue.

It does however work if I set src: './README.md' and run over just a single file. I've tried several variants of what src should accept and any that retrieve more than one file end up throwing an error when it comes to renaming.

Using latest grunt and grunt-markdown

FR: table of contents

I'd like to suggest generating a table of contents with marked-toc and making it available as an HTML ul/li tree in the template through <%=toc%>.

Am I making sense?

Thanks.

dest path always relative to src

My problem is, that I was unable to achieve a path relative to the Gruntfile.js in the root dir. grunt-markdown didn't stop to append the src dir name(s) to the dest names.

Here's my temporary work around to build a sane file name:

markdown : {
    dev : {
        files : [
            {
                expand : true,
                cwd    : '<%= site.mustache %>',
                src    : '<%= site.md %>/*.md',
                dest   : '<%= site.mustache %>/<%= site.mddeploy %>',
                ext    : '.mustache',
                rename : function ( dest, src ) {
                    var parts = src.split( '/' ),
                        file = parts[ parts.length -1 ],
                        final = dest + '/' +  file;

                    grunt.log.writeln( 'File created at: ' + final );

                    return final;
                }
            }
        ]
    }
}

Note: The grunt.log() is just a double confirmation that the callback returns the right thing. It's not necessary and you could instantly return dest + '/' + file.

I hope the current behavior is not intended. But if it is, I'd suggest adding above code to the README.md to tell people about it.

Related: #27 #42

Anyway, thanks for a plugin - it's really helpful for building docs :)

Code blocks not honoring `no-highlight`

The grunt-markdown plugin attempts to auto-highlight fenced blocks of code even if they are marked no-highlight, text, or plain. This should be possible using highlight.js, but for some reason doesn't work with grunt-markdown.

How to make highlight.js work?

I copy the config code of Gruntfile.js, and run grunt, but the output html does not have code highight effect. Please help.

Warning: 'Arguments to path.join must be string' causes compilation to fail

Hi,

Since updating my node version I'm getting this warning:

Warning: Arguments to path.join must be string

This is preventing the markdown from being compiled to HTML.

  • node -v = v0.10.22
  • ruby -v = ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin11.3.0]
  • grunt = ~0.4.1
  • grunt-markdown = ~0.4.0

Thanks,
Dan

dest parameter is not being used.

I'm having issues with the dest option not starting from the root of the project. For example, my Gruntfile.js looks something like this:

module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    markdown: {
      all: {
        files: [
          {
            expand: true,
            src: 'src/markdown/*.md',
            dest: 'src/html/',
            ext: '.html'
          }
        ]
      }
    },
    watch: {
    }
  });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-markdown');

  grunt.registerTask('default', ['markdown']);
};

When running grunt markdown, the files are generated into ./src/html/src/markdown/(filename).html. Is this the intended behavior? I tried a few different things in the dest option, such as "./src/html/" and "../../src/html", but it didn't change the output location.

How to link local images?

Assume we have such a directory structure

Project
|-- node_modules
|-- package.json
|-- htmls
|-- markdowns
|   `-- doc.md
`-- media
    `-- image.png

How do I refer to the image.png at my doc.md?

I tried ![image](../media/image.png) but it didn't work.

Thanks!

Should respect `markdown='1'` attributes for <div>s

i need to wrap some headlines (

-

) in a
with a specific class and want the content of the
to be parsed.

the accepted way to go seems to be this:

<div class="my-class" markdown="1">
# Haha
## Huhu
</div>

expected output:

<div class="my-class" markdown="1">
<h1>Haha</h1>
<h2>Huhu</h2>
</div>

what i get instead:

<div class="my-class" markdown="1">
# Haha
## Huhu
</div>

my current workaround (not closing the

, very hacky):

<div class="my-class" markdown="1">
# Haha
## Huhu

Cheers, Paul

2 vulnerabilities (npm audit)

                       === npm audit security report ===                        
                                                                                
┌──────────────────────────────────────────────────────────────────────────────┐
│                                Manual Review                                 │
│            Some vulnerabilities require your attention to resolve            │
│                                                                              │
│         Visit https://go.npm.me/audit-guide for additional guidance          │
└──────────────────────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Moderate      │ Prototype Pollution                                          │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ lodash                                                       │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=4.17.11                                                    │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ grunt-markdown [dev]                                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ grunt-markdown > lodash                                      │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://npmjs.com/advisories/782                             │
└───────────────┴──────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Low           │ Prototype Pollution                                          │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ lodash                                                       │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=4.17.5                                                     │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ grunt-markdown [dev]                                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ grunt-markdown > lodash                                      │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://npmjs.com/advisories/577                             │
└───────────────┴──────────────────────────────────────────────────────────────┘
found 2 vulnerabilities (1 low, 1 moderate) in 8388 scanned packages
  2 vulnerabilities require manual review. See the full report for details.

Updating the lodash dependency from ~2.4.1 to ^4.17.5 should resolve the issue, but may require some changes to code if the Lodash API changed significantly from version 2 to version 4.

Error while processing large number of files

I am using this task to convert 850+ markdown files. At a little over half way through the set the task encounters an error:

Fatal error: Unable to read "html/igOlapFlatDataSource_Adding.md,html/igOlapFlatDataSourace_Adding.md" file (Error code: ENOENT).

It seems to me that there is perhaps an issue in how the task is batching files and then reading them back out. What do you think?

marked dependencies

actually this plugin depends on "marked" nmp package but it is not traced nor provided.
i fixed the problem yust adding it to the npm_modules folder.

Modify default template by Grunt

Hi. Is there any way to change default template.jst in grunt config ?
I need to make something like this:

templateContext: {
    title: "My title"
}

But it is hardcoded. It would be nice to have it in .md file and after compilation add it to default template, but I don't know if it is possible, because as I know .md files and also data after compilation is stored in <%=content%>. Any idea how can I do it ?

Once again: I need to declare some data in .md file, and be able to add it dynamically into default template which is defined by template: "template.jst".

Thanks.

Pass in source file name

Can preCompile and postCompile be passed a 3rd argument that specifies the current filename? (either source or what it will be when done)

Using conditional logic in template

Which template engine is in use? I thought it was EJS - JavaScript Templates, but I cannot seem to make statements like

${if foo}
something
${/if}

or

<% if bar { %>
something else
<% } %>

to work.

Why "id" attribute is being generated on heading elements?

I see that this line of markdown:

This is a test of GFM for javascript

once converted to HTML becomes this:

<h1 id="this-is-a-test-of-gfm-for-javascript">This is a test of GFM for javascript</h1>

Which option is responsible for auto-generating id in heading elements and how can this be turned off?

Grunt 0.4 Release

I'm posting this issue to let you know that we will be publishing Grunt 0.4 on Monday, February 18th.

If your plugin is not already Grunt 0.4 compatible, would you please consider updating it? For an overview of what's changed, please see our migration guide.

If you'd like to develop against the final version of Grunt before Monday, please specify "grunt": "0.4.0rc8" as a devDependency in your project. After Monday's release, you'll be able to use "grunt": "~0.4.0" to actually publish your plugin. If you depend on any plugins from the grunt-contrib series, please see our list of release candidates for compatible versions. All of these will be updated to final status when Grunt 0.4 is published.

Also, in an effort to reduce duplication of effort and fragmentation in the developer community, could you review the grunt-contrib series of plugins to see if any of your functionality overlaps significantly with them? Grunt-contrib is community maintained with 40+ contributors—we'd love to discuss any additions you'd like to make.

Finally, we're working on a new task format that doesn't depend on Grunt: it's called node-task. Once this is complete, there will be one more conversion, and then we'll never ask you to upgrade your plugins to support our changes again. Until that happens, thanks for bearing with us!

If you have any questions about how to proceed, please respond here, or join us in #grunt on irc.freenode.net.

Thanks, we really appreciate your work!

title not working

This is possibly my ignorance, but when I tried to add in a title tag:

<title>foo</title>
more stuff here

When output, my content is all within a BODY block and therefore my title isn't correctly used.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.