Multiple Approaches to Hide Code in Jupyter Notebooks Rendered by NBViewer

Nov 24, 2025 · Programming · 11 views · 7.8

Keywords: Jupyter Notebook | NBViewer | Code Hiding | JavaScript | nbconvert

Abstract: This article comprehensively examines three primary methods for hiding code cells in Jupyter Notebooks when rendered by NBViewer: using JavaScript for interactive toggling, employing nbconvert command-line tools for permanent exclusion of code input, and leveraging metadata and tag systems within the Jupyter ecosystem. The paper analyzes the implementation principles, applicable scenarios, and limitations of each approach, providing complete code examples and configuration instructions. Addressing the current discrepancies in hidden cell handling across different Jupyter tools, the article also discusses standardization progress and best practice recommendations.

Introduction

Jupyter Notebook, as an interactive computing environment, has gained widespread adoption in data science, machine learning, and scientific research. However, when sharing notebooks through NBViewer, users often wish to conceal implementation details while displaying only the final analysis results and visual outputs. This requirement is particularly common in teaching demonstrations, technical reports, and成果展示 scenarios.

JavaScript Interactive Hiding Method

The JavaScript-based solution offers the most flexible approach to code hiding, allowing users to dynamically toggle code visibility during viewing. The core principle involves using jQuery selectors to target code cells and controlling their visibility through CSS display/hide properties.

The complete implementation code is as follows:

from IPython.display import HTML

HTML('''<script>
code_show=true; 
function code_toggle() {
 if (code_show){
 $('div.input').hide();
 } else {
 $('div.input').show();
 }
 code_show = !code_show
} 
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''')

The working mechanism of this code can be broken down into several steps: first, a global variable code_show is defined to track the current display state of the code. The function code_toggle() uses this state variable along with the jQuery selector $('div.input') to locate all code input cells, then calls the hide() or show() methods to control their visibility. $( document ).ready(code_toggle) ensures the hiding operation executes immediately after document loading, while the form element provides the user interaction interface.

The advantage of this method lies in its interactivity and immediacy, allowing users to view or hide code as needed. However, it relies on the client-side JavaScript execution environment and may be restricted under certain strict security policies.

NbConvert Command-Line Tool Method

For scenarios requiring static document generation, nbconvert provides a more thorough solution. Starting from version 5.2.1, nbconvert introduced content filtering capabilities that can permanently exclude specific types of cell content during conversion.

The basic command-line usage example is as follows:

jupyter nbconvert --to pdf --TemplateExporter.exclude_input=True my_notebook.ipynb

The parameter --TemplateExporter.exclude_input=True in this command instructs nbconvert to exclude all code input cells during conversion. Similar options include exclude_output for hiding output results, exclude_markdown for excluding Markdown cells, etc. These options support multiple output formats including HTML, PDF, and LaTeX, ensuring consistency in conversion results.

Compared to the JavaScript method, the nbconvert approach generates purely static content that doesn't rely on any client-side scripts, offering better compatibility and security. The disadvantage is the lack of interactivity - once conversion is complete, users can no longer view the hidden code content.

Metadata and Tag Systems in the Jupyter Ecosystem

Reference articles reveal the discrepancies and standardization challenges in hidden cell handling across different tools in the Jupyter ecosystem. JupyterLab uses specific metadata fields to control cell display states:

"metadata": {
  "collapsed": true,
  "jupyter": {
    "outputs_hidden": true,
    "source_hidden": true
  },
  "tags": []
}

Here, source_hidden controls the hiding of code input, outputs_hidden controls the hiding of output results, and collapsed provides basic folding functionality. This metadata-based approach complies with the nbformat specification but currently has limited support in NBViewer.

Jupyter Book adopts an alternative tag-based approach, using tags such as hide-input, hide-output, hide-cell to achieve similar hiding functionality, and remove-input, remove-output, remove-cell for permanent removal. The advantage of the tag system lies in its intuitiveness and ease of use, but inconsistencies in tag naming across different tools (such as hyphen vs underscore variations) have caused user confusion.

Method Comparison and Selection Recommendations

Each of the three main methods has its applicable scenarios: the JavaScript solution is suitable for online viewing scenarios requiring interactive control; the nbconvert solution is ideal for generating static reports and documents; while the metadata/tag approach feels more natural in JupyterLab and Jupyter Book environments.

In practical applications, users should choose the appropriate method based on specific requirements: for teaching demonstrations, JavaScript's interactivity may be more valuable; for formal reports, nbconvert-generated static documents are more reliable; and in JupyterBook projects, using the tag system provides the best native support.

Standardization Progress and Future Outlook

The current fragmented state of hidden cell functionality in the Jupyter ecosystem reflects natural phenomena during tool evolution. As reference articles point out, tools like JupyterLab, JupyterBook, nbconvert, and NBViewer exhibit differences in their API implementations for hiding cells, causing significant user confusion.

The community is actively promoting standardization efforts, with potential solutions including unified usage of jupyter metadata fields or establishing standard tag naming conventions. Users can contribute to this progress by participating in discussions and issue reporting in relevant GitHub repositories. As standards gradually unify, users will be able to more seamlessly share and present their notebook content across different tools in the future.

Conclusion

Hiding code in Jupyter Notebooks rendered by NBViewer offers multiple viable technical approaches, each with unique advantages and applicable scenarios. The JavaScript method provides the best interactive experience, the nbconvert approach ensures output purity, while metadata and tag systems represent the future direction of ecosystem development. Users should select the most suitable technical solution based on specific presentation needs and target audiences, while staying informed about the latest developments in Jupyter community standardization efforts.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.