pybabel ignoring files with autoescape - python

I have a python web application with jinja2 templates. I am using pybabel for localization. When using the pybabel extract command, it exports everything exactly as intended, EXCEPT for any files which use the jinja2 autoescape tag.
My babel.cfg file has the following line:
extensions=jinja2.ext.autoescape,jinja2.ext.with_
And the extract command I am using is:
pybabel extract -F ./babel.cfg -o ./locale/messages.pot ./
I have a file called settings.html, which has the following tag:
{% autoescape false %}
{% endautoescape %}
And pybabel lists this file in the console, in the list of files it extracts from:
extracting messages from templates/cfg/settings.html
But, when I check my pot file, there are no translations from settings.html.
If I delete the autoescape tag from settings.html, then re-run the pybabel extract command, then it correctly extracts the translations.
So there must be something up with use of autoescape.
Any clues?

Related

How to combine two mechanism for localization site written on Pelican?

I use two mechanisms for localization site:
1. I use the standard template tag {{ gettext 'some_text'}} in my index.html
2. I wrote custom jinja extension that takes the content of markdown file according to language that used on the site.
And I use Babel to create messages.pot file and then to create massages.po file.
I have this babel configuration in babel.cfg :
[jinja2: theme/templates/index.html]
silent = false
And this is my custom jinja extension - custom_jinja_extension.py :
from jinja2 import nodes
from jinja2.ext import Extension
from markdown import Markdown
class IncludeMarkdownExtension(Extension):
"""
a set of names that trigger the extension.
"""
tags = set(['include_markdown'])
def __init__(self, environment):
super(IncludeMarkdownExtension, self).__init__(environment)
def parse(self, parser):
tag = parser.stream.__next__()
ctx_ref = nodes.ContextReference()
if tag.value == 'include_markdown':
args = [ctx_ref, parser.parse_expression(), nodes.Const(tag.lineno)]
body = parser.parse_statements(['name:endinclude_markdown'], drop_needle=True)
callback = self.call_method('convert', args)
return nodes.CallBlock(callback, [], [], body).set_lineno(tag.lineno)
def convert(self, context, tagname, linenum, caller):
"""
Function for converting markdown to html
:param tagname: name of converting file
:return: converting html
"""
for item in context['extra_siteurls']:
if item == context['main_lang']:
input_file = open('content/{}/{}'.format('en', tagname))
else:
input_file = open('content/{}/{}'.format(context['main_lang'], tagname))
text = input_file.read()
html = Markdown().convert(text)
return html
I use this template tag - {% include_markdown 'slide3.md' %}{% endinclude_markdown %}
In my pelicanconf.py I add such strings for jinja extensions:
# Jinja2 extensions
JINJA_ENVIRONMENT = {
'extensions': [
'jinja2_markdown.MarkdownExtension',
'jinja2.ext.i18n',
'custom_jinja_extension.IncludeMarkdownExtension'
]
}
When I run the command:
pybabel extract --mapping babel.cfg --output messages.pot ./
I get this error
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag
'include_markdown'. Jinja was looking for the following tags:
'endblock'. The innermost block that needs to be closed is 'block'.
When I delete all using of custom template tag gettext work well. What I do wrong?
Trouble was in the path. Babel looking jinja extension in virtualenv in jinja folder, but my custom jinja extension was in the project folder.
That's why I run this command in the terminal
export PYTHONPATH=$PYTHONPATH:/local/path/to/the/project/
and change my babel.cfg :
[jinja2: theme/templates/index.html]
extensions=jinja2.ext.i18n, **custom_jinja_extension.IncludeMarkdownExtension**
silent = false
After this changes babel found my custom extension custom_jinja_extension and created messages.pot file correctly!

Jinja2 {% include file %} outside of search path doesn't work

This is an elementary issue which is probably related to Jinja2 PrefixLoader or ChoiceLoader.
On Python 3.6 we load with this command
jinja2.FileSystemLoader( searchpath= "\\template_folder\\")
On Windows 7, our file structure is as follows.
- folder_bbb
* subfile.txt
- template_folder
* template_file
- folder_aaa
* subfile.txt
From the template_file we are successful with this command
{% include "folder_aaa/subfile.txt" %}
Now we wish to move the file one level up, and write
{% include "../folder_bbb/subfile.txt" %}
but that doesn't work, complaining file not found.
What is the correct way to write? Thanks.
You may specify all paths in the the loader
jinja2.FileSystemLoader(["c:\\template_folder\\", "c:\\folder_bbb\\"])
and refer the including block without a specific path
{% include "subfile.txt" %}
The path will be searched in order so that as you say, moving the file one level up, the file will be found. (You need the template_folder path for the template itself.)

Remove the word "module" from Sphinx documentation

Using Sphinx for documenting my Python project. I want to remove the word "module" which follows the name of each python file (in the navbar, TOC, the page title, etc).
e.g. Details:
The project is composed of 2 files utils.py and main.py.
In my index.rst file, I use:
.. toctree::
:maxdepth: 2
utils
main
to import both files as "modules". From the docs/ folder, I then call:
sphinx-apidoc -f -o ./source/ ..
make html
to generate the static site. In the site, the word "module" follows every file name, and I would like to remove it.
Sphinx 2.2 adds templating for the reST files generated by sphinx-apidoc.
Use the --templatedir option to set the path to a dir containing module.rst_t, package.rst_t and toc.rst_t files. The files can be created from the corresponding files in site-packages/sphinx/templates/apidoc.
Then, in package.rst_treplace
{{- [submodule, "module"] | join(" ") | e | heading(2) }}
with
{{- submodule | e | heading(2) }}
Repeat for module.rst_t.
One possible solution uses JS to find & replace the word "module" after the page loads:
Create a file source/_templates/layout.html with the following content:
{% extends "!layout.html" %}
{% block extrahead %}
<script type="text/javascript">
window.onload = function() {
document.body.innerHTML = document.body.innerHTML.replace(/ module/g, '');
}
</script>
{% endblock %}
Make sure that conf.py has templates_path = ['_templates'] set, then Sphinx will append the script to the <head> of all documentation pages, and voila!

export notebook to pdf without code [duplicate]

This question already has answers here:
How to hide code from cells in ipython notebook visualized with nbviewer?
(23 answers)
Closed 4 years ago.
I have a large notebook with a lot of figures and text. I want to convert it to a html file. However, I don't want to export the code. I am using the following command
ipython nbconvert --to html notebook.ipynb
But this option also exports the code. Is there a way to convert the notebook to html without the code?
I found this article interesting it explains how to remove the input columns :
you have to create a template file named "hidecode.tplx" in same directory as the notebook you want to convert and add those line in it :
((*- extends 'article.tplx' -*))
((* block input_group *))
((*- if cell.metadata.get('nbconvert', {}).get('show_code', False) -*))
((( super() )))
((*- endif -*))
((* endblock input_group *))
And after run this command it will use pdfLatex to convert the notebook in pdf via latex:
jupyter nbconvert --to pdf --template hidecode Example.ipynb
or if you want to edit you can convert it to a .tex document and use pdfLatex to put it in pdf :
jupyter nbconvert --to latex --template hidecode Example.ipynb
EDIT Sept 2018:
ipython nbconvert is deprecated. It will be replaced by jupyter nbconvert: So we replace the command ipython with jupyter
EDIT Feb 2021: (This is my best answer here, so let me take care of it)
Following #Mrule comment adding --no-input flag will make it work without the template...
jupyter nbconvert --to latex --no-input Example.ipynb
PS: If you are getting issue saying :
LaTeX error related to tcolorbox.sty not found
Please refer to this guide to update your tex installation and this question
I was seeking the same question in SO and finally turned out to a very straightforward way:
Assuming using Firefox(57) + Win7
Run Jupyter notebook and download the notebook in the browser: File->Download as->HTML and you will get a html page with code and output.
Open the exported HTML with browser and activate the browser console with key F12
Run following command in the console:
document.querySelectorAll("div.input").forEach(function(a){a.remove()})
The code removes all input div DOM. Then right mouse button and chose "Save Page As" and Save the "Complete page" (not single page).
You will get a page with an associated folder in windows. Use a trick by zip the html page and then extract to unbind the associated. The folder is useless.
Now it is a single html page without code. You can re-distribute it or print it as PDF.
If you are not using Firefox or Windows, please adjust the above 3-6 steps.
Here is how I do it:
I simply download my notebook as html.
Then run this python script to convert that html file so that prompts and code cells are gone:
FILE = "/somewhere/myHTMLFile.html"
with open(FILE, 'r') as html_file:
content = html_file.read()
# Get rid off prompts and source code
content = content.replace("div.input_area {","div.input_area {\n\tdisplay: none;")
content = content.replace(".prompt {",".prompt {\n\tdisplay: none;")
f = open(FILE, 'w')
f.write(content)
f.close()
That script bascially adds the CSS 'display: none' attribute for all divs of class 'prompt' or 'input_area'.
As a generalization of this answer, so that hidecode template could be accessible from multiple locations:
Go into your home directory:
cd ~/.jupyter
Create jupyter_nbconvert_config.py under this directory.
Write the following into the .py file (Change user_name to your user name):
c = get_config()
c.TemplateExporter.template_path = ['.', "~/.jupyter" ]
c.LatexExporter.template_path = ['.', "~/.jupyter"]
Create a template file under this directory, named hidecode.tplx or hidecode.tpl:
((*- extends 'article.tplx' -*))
((* block input_group *))
((*- if cell.metadata.get('nbconvert', {}).get('show_code', False) -*))
((( super() )))
((*- endif -*))
((* endblock input_group *))
Then, the following should generate a PDF without .ipynb files' codes (Change file_name to your file name):
jupyter nbconvert --to pdf '<file_name>.ipynb' --template=hidecode.tpl
You can add this css to your page and then print into PDF from the browser. Note that the code is only hidden, not removed.
div.output_prompt { visibility: hidden; }
*{ font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif !important }
.input,#header { display: none; }
To make sure you remove the code you should use something like
$(".input").remove()
As far as I know there is no way to generate via latex a PDF that does not include the code. It would be great to have a jupyter notebook extension that does it though...
nbconvert uses templates to convert the notebook's JSON into a document; for example, in the markdown template that comes with nbconvert, markdown.tpl:
{% block input %}
{% if nb.metadata.language_info %}{{ nb.metadata.language_info.name }}{% endif %}
{{ cell.source}}
{% endblock input %}
which prints each cell's source in the output. If you delete {{ cell.source}} then the cell source will not print out. There are corresponding blocks in the HTML and Latex templates as well.
Better yet, make your own template that does exactly what you want :)

Caught ViewDoesNotExist while rendering

I have encountered an error:
Caught ViewDoesNotExist while rendering: Tried my_view_two in module yourmodule.views. Error was: 'module' object has no attribute 'my_view_two'
The error is triggered from template tag:
{% trans "Lost your password?" %}
Earlier I have my_view_two function and added that in urls.py too. But later I deleted the URL entry and function. But it is still giving an error.
I have had similar errors reporting on {% url password_reset_link %} before - is that the first {% url %} in your template by any chance?
It looks as if that view is being imported somewhere (perhaps elsewhere from the urls.py?). Have you imported that view into another views.py file for example?). A quick way to find files containing this is to use grep (on Linux/Mac) at a command line in your site root:
$ grep -r "my_view_two" .
This will search for that string in all files of your project (if I've understood you correctly, it shouldn't be there).

Categories