Skip to content

Instantly share code, notes, and snippets.

@QuentinAndre
Created September 13, 2019 11:30
Show Gist options
  • Save QuentinAndre/75fb32f76720546550f672133969213e to your computer and use it in GitHub Desktop.
Save QuentinAndre/75fb32f76720546550f672133969213e to your computer and use it in GitHub Desktop.
A Jupyter NBConvert HTML template adding a toggle to hide/show each code cell.
# Typical usage: The --no-prompt is important (layout is all messed up otherwise).
jupyter nbconvert MySuperNotebook.ipynb --to html --no-prompt --template code_cells_toggle.tpl
# By default, all cells are hidden. You can override this behavior for some cells by giving them a 'code_shown' tag.
{% extends 'full.tpl' %}
{% 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 %}
@idavydov
Copy link

idavydov commented Mar 4, 2021

I was running into TemplateNotFound error. Here's my updated version. Seem to work fine.
https://gist.github.com/idavydov/1a27e902ad2df35c93fad57fe9894792

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