How to print all contents of Hugo in single page similar Rust book print.html

314 views Asked by At

A print button is provided in the Rust book. After clicking it, a single page is created from all contents and printing options are displayed.

https://doc.rust-lang.org/book/print.html

For Hugo template, I want to create a printed page similar to the Rust book and I checked Custom Output Format but doesn't find solution for solve this issue.

2

There are 2 answers

0
Jeremie On BEST ANSWER

Here is the code I use to list all the content of a website. It may not do exactly what you want, but I think that by tweaking it a bit, you should get what you need.

This code loops through the sections of the site. It displays each section page with its title and content. Then loop through the section child pages and display each of them

{{ range .Site.Home.Sections }}
    <h1>{{ .Title }}</h1>
    <hr />
    {{ range .Pages }}
    {{ .Content }}
    <hr />
    {{ end }}
    {{ range .Sections }}
        <h1>{{ .Title }}</h1>
        <hr />
        {{ range .Pages }}
            {{ .Content }}
            <hr />
        {{ end }}
    {{ end }}
{{ end }}

Notes:

  1. The issue I faced is that the pages may not be in the logical order you would like to see them. You can add sortering / filtering conditions in each of the section.

  2. The code is not perfect, as it uses several H1 markups. This is due to the fact that in Hugo, most of the time, the title of the page is displayed with H1, and the .Content contains H2/H3/H4.

I made it to be able to print my whole site on paper and review its content. I won't use this on a page that you intend to rank, as the multiple H1 might puzzle search engines, as well as create duplicate content.

2
Andrei Mustata On

The sort of "brute-force" solution would be to create a print.html template.

1. Content

In your print.html template, you would iterate through all your content in whatever order you need, so that it's all in the single page.

2. Styling

You probably want some custom styling, so you can add a <link href="..." media="print" rel="stylesheet" />, or some @media print in your stylesheet.

3. Print-dialog

Once the content is loaded on the page, you can window.print(), and that will bring up the browser's print dialog box.

Sources

  1. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-media
  2. https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries
  3. https://developer.mozilla.org/en-US/docs/Web/API/Window/print