Skip to content

Instantly share code, notes, and snippets.

@idavydov
Forked from QuentinAndre/README.txt
Last active November 8, 2023 19:18
Show Gist options
  • Save idavydov/1a27e902ad2df35c93fad57fe9894792 to your computer and use it in GitHub Desktop.
Save idavydov/1a27e902ad2df35c93fad57fe9894792 to your computer and use it in GitHub Desktop.
A Jupyter NBConvert HTML template adding a toggle to hide/show each code cell.
# You need to put index.html.j2 & conf.json into a directory called, e.g., mytmpl/.
# Typical usage: The --no-prompt is important (layout is all messed up otherwise).
jupyter nbconvert MySuperNotebook.ipynb --to html --no-prompt --template mytmpl/
# By default, all cells are hidden. You can override this behavior for some cells by giving them a 'code_shown' tag.
{
"base_template": "lab",
"mimetypes": {
"text/html": true
},
"preprocessors": {
"100-pygments": {
"type": "nbconvert.preprocessors.CSSHTMLHeaderPreprocessor",
"enabled": true
}
}
}
{% extends 'lab/index.html.j2' %}
{% block html_head %}
{{ super() }}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$('.code_shower').on('click',function(){
var header = $(this);
var codecell = $(this).next()
codecell.slideToggle(0, function() {
if (codecell.is(':hidden')) {
header.text("Show Code");
header.css("border-radius", "2px 2px 2px 2px");
} else {
header.text("Hide Code");
header.css("border-radius", "2px 2px 0px 0px")
}
});
});
$('.hidden_default').next().hide();
});
</script>
<style>
div.input {
flex-direction: column !important;
}
div.input_area {
border-radius: 0px 0px 2px 2px;
}
div.code_shower {
background: lightgray;
padding: 5px 10px;
cursor: pointer;
border-radius: 2px 2px 0px 0px;
}
</style>
{% endblock html_head %}
{% block input %}
{% if 'code_shown' in cell['metadata'].get('tags', []) %}
<div class="code_shower">Hide Code</div>
{% else %}
<div class="code_shower hidden_default">Show Code</div>
{% endif %}
{{ super() }}
{% endblock input %}
{% block output_prompt %}
{% endblock output_prompt %}
{% block in_prompt %}
{% endblock in_prompt %}
@quocdat-le-insacvl
Copy link

It works for me.
Can you also support RST? It's gonna be great.
Thank you a lot!

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