【问题标题】:Where is custom.css in the generated html file from nbconvert?从 nbconvert 生成的 html 文件中的 custom.css 在哪里?
【发布时间】:2020-06-26 03:31:23
【问题描述】:

我正在使用 nbconvert 将我的 jupyter notebook 转换为 html by

jupyter nbconvert my.ipynb --to html

然后它说:

[NbConvertApp] 将笔记本 my.ipynb 转换为 html [NbConvertApp] 将 407497 字节写入 my.html

然后在生成的my.html中,可以看到需要custom.css

<!-- Custom stylesheet, it must be in the same directory as the html file -->
<link rel="stylesheet" href="custom.css">

<!-- Loading mathjax macro -->
<!-- Load mathjax -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS_HTML"></script>
    <!-- MathJax configuration -->
    <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ['$','$'], ["\\(","\\)"] ],
            displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
            processEscapes: true,
            processEnvironments: true
        },
        // Center justify equations in code and markdown cells. Elsewhere
        // we use CSS to left justify single line equations in code cells.
        displayAlign: 'center',
        "HTML-CSS": {
            styles: {'.MathJax_Display': {"margin": 0}},
            linebreaks: { automatic: true }
        }
    });
    </script>

信息: nbconvert 版本为5.6.1

谢谢

【问题讨论】:

    标签: html css jupyter-notebook nbconvert


    【解决方案1】:

    如果您唯一的问题是这一行:&lt;link rel="stylesheet" href="custom.css"&gt;,您可以修改模板文件并编写自定义 HTML 导出器:

    导航到 nbconvert 的源目录。转到./templates/html/。将有一个名为full.tpl 的文件。这用作 HTML 文件的模板。使用文本编辑器打开文件并删除&lt;link rel="stylesheet" href="custom.css"&gt; 行。 使用扩展名.tpl (fullcustom.tpl) 保存文件。确保将其保存在与full.tpl 相同的目录中。

    下一步是在 Python 中编写自定义导出器类(推荐)。你必须继承./exporters/html.py 中定义的HTMLExporter 类。您可以按照此处描述的过程进行操作:https://nbconvert.readthedocs.io/en/latest/external_exporters.html

    现在,如果你不想花时间做这件事,一个快速的“kludge”将是实际修改HTMLExporter 类。如果您愿意,可以创建一个 html.py 文件的副本,因为它正在被修改。打开./exporters/html.py,在HTMLExporter类中找到如下方法:

    @default('template_file')
        def _template_file_default(self):
            return 'full.tpl'
    

    return full.tpl 更改为您使用 (fullcustom.tpl) 保存修改后的 full.tpl 版本的名称。

    【讨论】:

      【解决方案2】:

      如果文件custom.css 存在于同一目录中,&lt;link rel="stylesheet" href="custom.css"&gt; 会有效地包含自定义 CSS 样式规则。

      如果您想要一些自定义的 CSS 样式规则来显示生成的 html。您可以在与 html 文件相同的目录中添加具有这些规则的文件 custom.css

      这不是强制性要求。如果您不想要任何自定义样式规则,可以不包含这样的文件。生成的 HTML 文件中的默认 CSS 规则仍然有效。

      【讨论】:

      • 这里的用例是我将笔记本转换为 html 将提供给浏览器。问题是如果我将 html 文件返回到浏览器,该浏览器将尝试自动获取 css 文件。我试图避免这种多余的获取,因为服务器端不存在 css 文件。
      • 我建议您自己从生成的 html 文件中删除该行。如果有很多 html 文件,您可以使用 sed -i '/link.*custom\.css/d' generated_html/*.html 之类的方式轻松(在 linux 上)自动执行此操作
      • 这是我决定使用的解决方案。我的用例不是以性能为中心的,所以我可以采用这种 hacky 方式来提供 html。但如果您的用例更注重性能,请使用 Amal K 的解决方案。
      猜你喜欢
      • 1970-01-01
      • 2014-09-12
      • 1970-01-01
      • 2015-03-18
      • 1970-01-01
      • 2012-01-31
      • 2016-08-08
      • 2012-12-23
      • 1970-01-01
      相关资源
      最近更新 更多