Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
pkgdown nicely renders code chunks in your package documentation. However, if you mix in non-R snippets, it gets difficult to distinguish between languages. So how about some nice labels for each code box.
pkgdown is super useful for documenting your R packages. It is particularly well suited to showcase small code examples. In some of my projects, on top of R code chunks, I also provide code examples in other languages such as short Linux command line code snippets I used to preprocess data before loading it into R.
pkgdown renders code chunks in most common languages nicely, with syntax highlighting, etc. However, it does not indicate what language is used in a particular code chunk. For most projects, this is not a problem, because all code chunks are R code anyway. But this behavior gets confusing when we mix different languages in the same document.
To solve this issue, I wrote a small javascript hook that adds small labels to
each code chunk, indicating the language of its content. The hook comprises a
short jQuery function and some CSS instructions. Simply add the two snippets
below to your pkgdown/extra.js
and pkgdown/extra.css
to add the labels to
your pkgdown projects.
// add to extra.js function addLang( jQuery ) { $("div.sourceCode").each(function(i, v){ var lang = $(this).children("pre").attr("class").split(' ').pop() var Lang = lang[0].toUpperCase() + lang.slice(1) $(this).before('<div class="codelabel ' + lang + '">' + Lang + ' code</div>' + '<div class="codelabelspacer"></div>') }) } $( document ).ready(addLang)
/* add to extra.css */ codelabel { border: 2px solid white; background-color: #eee; z-index: 100; position: absolute; -size: 60%; -weight: bold; padding: 2px; display: inline-block; } .codelabelspacer { height: 12px; }
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.