本文整理汇总了Python中sphinx.jinja2glue.BuiltinTemplateLoader类的典型用法代码示例。如果您正苦于以下问题:Python BuiltinTemplateLoader类的具体用法?Python BuiltinTemplateLoader怎么用?Python BuiltinTemplateLoader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BuiltinTemplateLoader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_template_env
def get_template_env(self):
'''Create jinja template environment'''
env = self.state.document.settings.env
current_dir = os.path.dirname(__file__)
template_dirs = [os.path.join(current_dir, 'flaskSphinx_templates'), current_dir]
template_loader = BuiltinTemplateLoader()
template_loader.init(env.app.builder, dirs=template_dirs)
return SandboxedEnvironment(loader=template_loader)
示例2: __init__
def __init__(self, app):
template_loader = BuiltinTemplateLoader()
template_loader.init(app.builder)
template_env = SandboxedEnvironment(loader=template_loader)
template_env.filters['escape'] = escape_filter
template_env.filters['underline'] = underline_filter
template_env.filters['as_extlink'] = as_extlink_filter
self.env = template_env
self.templates = {}
示例3: MakoBridge
class MakoBridge(TemplateBridge):
def init(self, builder, *args, **kw):
self.jinja2_fallback = BuiltinTemplateLoader()
self.jinja2_fallback.init(builder, *args, **kw)
builder.config.html_context['site_base'] = builder.config['site_base']
self.lookup = TemplateLookup(
directories=builder.config.templates_path,
imports=[
"from builder import util"
],
#format_exceptions=True,
)
def render(self, template, context):
template = template.replace(".html", ".mako")
context['prevtopic'] = context.pop('prev', None)
context['nexttopic'] = context.pop('next', None)
# RTD layout
if rtd:
# add variables if not present, such
# as if local test of READTHEDOCS variable
if 'MEDIA_URL' not in context:
context['MEDIA_URL'] = "http://media.readthedocs.org/"
if 'slug' not in context:
context['slug'] = "mako-test-slug"
if 'url' not in context:
context['url'] = "/some/test/url"
if 'current_version' not in context:
context['current_version'] = "some_version"
if 'versions' not in context:
context['versions'] = [('default', '/default/')]
context['docs_base'] = "http://readthedocs.org"
context['toolbar'] = True
context['layout'] = "rtd_layout.mako"
context['pdf_url'] = "%spdf/%s/%s/%s.pdf" % (
context['MEDIA_URL'],
context['slug'],
context['current_version'],
context['slug']
)
# local docs layout
else:
context['toolbar'] = False
context['docs_base'] = "/"
context['layout'] = "layout.mako"
context.setdefault('_', lambda x:x)
return self.lookup.get_template(template).render_unicode(**context)
def render_string(self, template, context):
# this is used for .js, .css etc. and we don't have
# local copies of that stuff here so use the jinja render.
return self.jinja2_fallback.render_string(template, context)
示例4: __init__
def __init__(self, app, extra_context):
template_loader = BuiltinTemplateLoader()
template_loader.init(app.builder)
template_env = SandboxedEnvironment(loader=template_loader)
template_env.filters['rst_escape'] = rst_escape_filter
template_env.filters['underline'] = underline_filter
template_env.filters['as_extlink'] = as_extlink_filter
template_env.filters['prefixes'] = prefixes_filter
template_env.filters['rst_link'] = rst_link_filter
self.env = template_env
self.templates: Dict[str, Any] = {}
self.extra_context = extra_context
示例5: MakoBridge
class MakoBridge(TemplateBridge):
def init(self, builder, *args, **kw):
self.jinja2_fallback = BuiltinTemplateLoader()
self.jinja2_fallback.init(builder, *args, **kw)
builder.config.html_context['release_date'] = builder.config['release_date']
builder.config.html_context['site_base'] = builder.config['site_base']
self.lookup = TemplateLookup(directories=builder.config.templates_path,
#format_exceptions=True,
imports=[
"from builder import util"
]
)
if rtd:
# RTD layout, imported from sqlalchemy.org
import urllib2
template = urllib2.urlopen(builder.config['site_base'] + "/docs_adapter.mako").read()
self.lookup.put_string("docs_adapter.mako", template)
setup_ctx = urllib2.urlopen(builder.config['site_base'] + "/docs_adapter.py").read()
lcls = {}
exec(setup_ctx, lcls)
self.setup_ctx = lcls['setup_context']
def setup_ctx(self, context):
pass
def render(self, template, context):
template = template.replace(".html", ".mako")
context['prevtopic'] = context.pop('prev', None)
context['nexttopic'] = context.pop('next', None)
# local docs layout
context['rtd'] = False
context['toolbar'] = False
context['base'] = "static_base.mako"
# override context attributes
self.setup_ctx(context)
context.setdefault('_', lambda x: x)
return self.lookup.get_template(template).render_unicode(**context)
def render_string(self, template, context):
# this is used for .js, .css etc. and we don't have
# local copies of that stuff here so use the jinja render.
return self.jinja2_fallback.render_string(template, context)
示例6: get_template_env
def get_template_env(app):
"""
Get the template environment.
.. note::
Template should be loaded as a package_data using
:py:function:`pkgutil.get_data`, but because we want the user to
override the default template we need to hook it to the Sphinx loader,
and thus a file system approach is required as it is implemented like
that.
"""
template_dir = [join(dirname(abspath(__file__)), 'templates')]
template_loader = BuiltinTemplateLoader()
template_loader.init(app.builder, dirs=template_dir)
template_env = SandboxedEnvironment(loader=template_loader)
template_env.filters['summary'] = filter_summary
return template_env
示例7: init
def init(self, builder, *args, **kw):
self.jinja2_fallback = BuiltinTemplateLoader()
self.jinja2_fallback.init(builder, *args, **kw)
builder.config.html_context['site_base'] = builder.config['site_base']
self.lookup = TemplateLookup(
directories=builder.config.templates_path,
imports=[
"from builder import util"
]
)
示例8: init
def init(self, builder, *args, **kw):
self.jinja2_fallback = BuiltinTemplateLoader()
self.jinja2_fallback.init(builder, *args, **kw)
builder.config.html_context["release_date"] = builder.config["release_date"]
builder.config.html_context["site_base"] = builder.config["site_base"]
self.lookup = TemplateLookup(
directories=builder.config.templates_path,
# format_exceptions=True,
imports=["from builder import util"],
)
if rtd:
import urllib2
template_url = builder.config["site_base"] + "/docs_base.mako"
template = urllib2.urlopen(template_url).read()
self.lookup.put_string("/rtd_base.mako", template)
示例9: init
def init(self, builder, *args, **kw):
self.jinja2_fallback = BuiltinTemplateLoader()
self.jinja2_fallback.init(builder, *args, **kw)
builder.config.html_context['release_date'] = builder.config['release_date']
builder.config.html_context['site_base'] = builder.config['site_base']
self.lookup = TemplateLookup(directories=builder.config.templates_path,
#format_exceptions=True,
imports=[
"from builder import util"
]
)
if rtd:
# RTD layout, imported from sqlalchemy.org
import urllib2
template = urllib2.urlopen(builder.config['site_base'] + "/docs_adapter.mako").read()
self.lookup.put_string("docs_adapter.mako", template)
setup_ctx = urllib2.urlopen(builder.config['site_base'] + "/docs_adapter.py").read()
lcls = {}
exec(setup_ctx, lcls)
self.setup_ctx = lcls['setup_context']
示例10: add_content
def add_content(self, more_content, no_docstring=False):
if self.doc_as_attr:
super(GWpyClassDocumenter, self).add_content(
more_content, no_docstring=no_docstring)
else:
name = safe_getattr(self.object, '__name__', None)
if name:
# create our own templating environment
builder = self.env.app.builder or None
template_dirs = [os.path.join(package_dir, 'ext',
'autosummary', 'templates')]
if builder is not None:
if builder.config.templates_path:
template_dirs = (builder.config.templates_path +
template_dirs)
# allow the user to override the templates
template_loader = BuiltinTemplateLoader()
template_loader.init(builder, dirs=template_dirs)
else:
template_loader = FileSystemLoader(template_dirs)
template_env = SandboxedEnvironment(loader=template_loader)
template = template_env.get_template('autoclass/class.rst')
def get_members(obj, typ, include_public=[]):
items = []
want_all = self.options.inherited_members or \
self.options.members is ALL
members = zip(*self.get_object_members(want_all)[1])[0]
if self.options.exclude_members:
members = [m for m in members if
m not in self.options.exclude_members]
for name in members:
try:
documenter = get_documenter(safe_getattr(obj, name),
obj)
except AttributeError:
continue
if documenter.objtype == typ:
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
return public, items
ns = {}
config = self.env.app.config
npconfig = dict(
use_plots=config.numpydoc_use_plots,
show_class_members=config.numpydoc_show_class_members)
ns['docstring'] = SphinxClassDoc(self.object, config=npconfig)
ns['members'] = vars(self.object)
ns['methods'], ns['all_methods'] = get_members(self.object,
'method',
['__init__'])
ns['attributes'], ns['all_attributes'] = get_members(
self.object, 'attribute')
parts = self.fullname.split('.')
mod_name, obj_name = '.'.join(parts[:-1]), parts[-1]
ns['fullname'] = name
ns['module'] = mod_name
ns['objname'] = obj_name
ns['name'] = parts[-1]
for line in template.render(**ns).split('\n'):
if line not in [None, 'None']:
self.add_line(line, '<autodoc>')
self.doc_as_attr = True
示例11: generate_autosummary_docs
def generate_autosummary_docs(
sources,
output_dir=None,
suffix=".rst",
warn=_simple_warn,
info=_simple_info,
base_path=None,
builder=None,
template_dir=None,
):
showed_sources = list(sorted(sources))
if len(showed_sources) > 20:
showed_sources = showed_sources[:10] + ["..."] + showed_sources[-10:]
info("[autosummary] generating autosummary for: %s" % ", ".join(showed_sources))
if output_dir:
info("[autosummary] writing to %s" % output_dir)
if base_path is not None:
sources = [os.path.join(base_path, filename) for filename in sources]
# create our own templating environment
template_dirs = [os.path.join(package_dir, "ext", "autosummary", "templates")]
if builder is not None:
# allow the user to override the templates
template_loader = BuiltinTemplateLoader()
template_loader.init(builder, dirs=template_dirs)
else:
if template_dir:
template_dirs.insert(0, template_dir)
template_loader = FileSystemLoader(template_dirs)
template_env = SandboxedEnvironment(loader=template_loader)
# read
items = find_autosummary_in_files(sources)
# remove possible duplicates
items = dict([(item, True) for item in items]).keys()
# keep track of new files
new_files = []
# write
for name, path, template_name in sorted(items):
if path is None:
# The corresponding autosummary:: directive did not have
# a :toctree: option
continue
path = output_dir or os.path.abspath(path)
ensuredir(path)
try:
name, obj, parent = import_by_name(name)
except ImportError, e:
warn("[autosummary] failed to import %r: %s" % (name, e))
continue
fn = os.path.join(path, name + suffix)
# skip it if it exists
if os.path.isfile(fn):
continue
new_files.append(fn)
f = open(fn, "w")
try:
doc = get_documenter(obj, parent)
if template_name is not None:
template = template_env.get_template(template_name)
else:
try:
template = template_env.get_template("autosummary/%s.rst" % doc.objtype)
except TemplateNotFound:
template = template_env.get_template("autosummary/base.rst")
def get_members(obj, typ, include_public=[]):
items = []
for name in dir(obj):
if sys.skip_member(name, obj):
continue
if typ in ["class", "function"]:
c = getattr(obj, name)
if inspect.isclass(c) or inspect.isfunction(c):
if c.__module__ != obj.__name__ + ".base" and c.__module__ != obj.__name__:
continue
try:
documenter = get_documenter(safe_getattr(obj, name), obj)
except AttributeError:
continue
if documenter.objtype == typ:
items.append(name)
public = [x for x in items if x in include_public or not x.startswith("_")]
return public, items
#.........这里部分代码省略.........
示例12: generate_autosummary_docs
def generate_autosummary_docs(
sources, output_dir=None, suffix='.rst', warn=_simple_warn,
info=_simple_info, base_path=None, builder=None, template_dir=None,
app=None):
showed_sources = list(sorted(sources))
if len(showed_sources) > 20:
showed_sources = showed_sources[:10] + ['...'] + showed_sources[-10:]
info('[autosummary] generating autosummary for: %s' %
', '.join(showed_sources))
if output_dir:
info('[autosummary] writing to %s' % output_dir)
if base_path is not None:
sources = [osp.join(base_path, filename) for filename in sources]
# create our own templating environment
template_dirs = [osp.join(package_dir, 'ext', 'autosummary', 'templates')]
if builder is not None:
# allow the user to override the templates
template_loader = BuiltinTemplateLoader()
template_loader.init(builder, dirs=template_dirs)
else:
if template_dir:
template_dirs.insert(0, template_dir)
template_loader = FileSystemLoader(template_dirs)
template_env = SandboxedEnvironment(loader=template_loader)
# read
items = find_autosummary_in_files(sources)
# remove possible duplicates
items = list(dict([(item, True) for item in items]).keys())
# keep track of new files
new_files = []
# write
# noinspection PyTypeChecker
for name, path, template_name in sorted(items, key=str):
if path is None:
# The corresponding autosummary:: directive did not have
# a :toctree: option
continue
path = output_dir or osp.abspath(path)
ensuredir(path)
try:
name, obj, parent, mod_name = import_by_name(name)
except ImportError as e:
warn('[autosummary] failed to import %r: %s' % (name, e))
continue
fn = osp.join(path, name + suffix)
# skip it if it exists
if osp.isfile(fn):
continue
new_files.append(fn)
f = open(fn, 'w')
try:
try:
doc = get_documenter(app, obj, parent)
except TypeError:
doc = get_documenter(obj, parent)
if template_name is not None:
template = template_env.get_template(template_name)
else:
try:
template = template_env.get_template('autosummary/%s.rst'
% doc.objtype)
except TemplateNotFound:
template = template_env.get_template('autosummary/base.rst')
ns = {}
if doc.objtype == 'module':
ns['members'] = dir(obj)
ns['functions'], ns['all_functions'] = \
get_members(app, obj, 'function')
ns['classes'], ns['all_classes'] = \
get_members(app, obj, 'class')
ns['exceptions'], ns['all_exceptions'] = \
get_members(app, obj, 'exception')
ns['data'], ns['all_data'] = \
get_members(app, obj, 'data', imported=True)
ns['data'] = ', '.join(ns['data'])
ns['all_data'] = ', '.join(ns['all_data'])
ns['dispatchers'], ns['all_dispatchers'] = \
get_members(app, obj, 'dispatcher', imported=True)
elif doc.objtype == 'class':
ns['members'] = dir(obj)
ns['methods'], ns['all_methods'] = \
#.........这里部分代码省略.........
示例13: generate_autosummary_docs
def generate_autosummary_docs(
sources,
output_dir=None,
suffix=".rst",
warn=_simple_warn,
info=_simple_info,
base_path=None,
builder=None,
template_dir=None,
):
showed_sources = list(sorted(sources))
if len(showed_sources) > 20:
showed_sources = showed_sources[:10] + ["..."] + showed_sources[-10:]
info("[autosummary] generating autosummary for: %s" % ", ".join(showed_sources))
if output_dir:
info("[autosummary] writing to %s" % output_dir)
if base_path is not None:
sources = [os.path.join(base_path, filename) for filename in sources]
# create our own templating environment
template_dirs = [os.path.join(os.path.dirname(__file__), "templates")]
if builder is not None:
# allow the user to override the templates
template_loader = BuiltinTemplateLoader()
template_loader.init(builder, dirs=template_dirs)
else:
if template_dir:
template_dirs.insert(0, template_dir)
template_loader = FileSystemLoader(template_dirs)
template_env = SandboxedEnvironment(loader=template_loader, extensions=["jinja2.ext.do"])
# read
items = find_autosummary_in_files(sources)
# remove possible duplicates
items = dict([(item, True) for item in items]).keys()
# keep track of new files
new_files = []
# write
for name, path, template_name in sorted(items):
if path is None:
# The corresponding autosummary:: directive did not have
# a :toctree: option
continue
path = output_dir or os.path.abspath(path)
ensuredir(path)
try:
name, obj, parent = import_by_name(name)
except ImportError, e:
warn("[autosummary] failed to import %r: %s" % (name, e))
continue
fn = os.path.join(path, name + suffix)
# skip it if it exists
if os.path.isfile(fn):
continue
new_files.append(fn)
f = open(fn, "w")
try:
doc = get_documenter(obj, parent)
if template_name is not None:
template = template_env.get_template(template_name)
else:
try:
template = template_env.get_template("autosummary/%s.rst" % doc.objtype)
except TemplateNotFound:
template = template_env.get_template("autosummary/base.rst")
def get_members(obj, typ, include_public=[]):
# XXX: whole function is a patch!
if typ in ("function", "class", "exception"):
# modules seem to work
items = [name for name in dir(obj) if get_documenter(getattr(obj, name), obj).objtype == typ]
items = [name for name in items if getattr(obj, name).__module__ == obj.__name__]
elif typ == "method":
# filter methods (__call__) which are defined within this
# class (im_class)
items = [
name
for name in dir(obj)
if hasattr(getattr(obj, name), "__call__") and hasattr(getattr(obj, name), "im_class")
]
elif typ == "attribute":
# attribute
items = [name for name in dir(obj) if not hasattr(getattr(obj, name), "__call__")]
public = [x for x in items if not x.startswith("_") or x.endswith("__")]
return public, items
#.........这里部分代码省略.........
示例14: generate_automodsumm_docs
def generate_automodsumm_docs(lines, srcfn, suffix='.rst', warn=None,
info=None, base_path=None, builder=None,
template_dir=None):
"""
This function is adapted from
`sphinx.ext.autosummary.generate.generate_autosummmary_docs` to
generate source for the automodsumm directives that should be
autosummarized. Unlike generate_autosummary_docs, this function is
called one file at a time.
"""
from sphinx.jinja2glue import BuiltinTemplateLoader
from sphinx.ext.autosummary import import_by_name, get_documenter
from sphinx.ext.autosummary.generate import (find_autosummary_in_lines,
_simple_info, _simple_warn)
from sphinx.util.osutil import ensuredir
from sphinx.util.inspect import safe_getattr
from jinja2 import FileSystemLoader, TemplateNotFound
from jinja2.sandbox import SandboxedEnvironment
if info is None:
info = _simple_info
if warn is None:
warn = _simple_warn
#info('[automodsumm] generating automodsumm for: ' + srcfn)
# Create our own templating environment - here we use Astropy's
# templates rather than the default autosummary templates, in order to
# allow docstrings to be shown for methods.
template_dirs = [os.path.join(os.path.dirname(__file__), 'templates'),
os.path.join(base_path, '_templates')]
if builder is not None:
# allow the user to override the templates
template_loader = BuiltinTemplateLoader()
template_loader.init(builder, dirs=template_dirs)
else:
if template_dir:
template_dirs.insert(0, template_dir)
template_loader = FileSystemLoader(template_dirs)
template_env = SandboxedEnvironment(loader=template_loader)
# read
#items = find_autosummary_in_files(sources)
items = find_autosummary_in_lines(lines, filename=srcfn)
if len(items) > 0:
msg = '[automodsumm] {1}: found {0} automodsumm entries to generate'
info(msg.format(len(items), srcfn))
# gennms = [item[0] for item in items]
# if len(gennms) > 20:
# gennms = gennms[:10] + ['...'] + gennms[-10:]
# info('[automodsumm] generating autosummary for: ' + ', '.join(gennms))
# remove possible duplicates
items = dict([(item, True) for item in items]).keys()
# keep track of new files
new_files = []
# write
for name, path, template_name in sorted(items):
if path is None:
# The corresponding autosummary:: directive did not have
# a :toctree: option
continue
path = os.path.abspath(path)
ensuredir(path)
try:
import_by_name_values = import_by_name(name)
except ImportError as e:
warn('[automodsumm] failed to import %r: %s' % (name, e))
continue
# if block to accommodate Sphinx's v1.2.2 and v1.2.3 respectively
if len(import_by_name_values) == 3:
name, obj, parent = import_by_name_values
elif len(import_by_name_values) == 4:
name, obj, parent, module_name = import_by_name_values
fn = os.path.join(path, name + suffix)
# skip it if it exists
if os.path.isfile(fn):
continue
new_files.append(fn)
f = open(fn, 'w')
try:
doc = get_documenter(obj, parent)
if template_name is not None:
template = template_env.get_template(template_name)
else:
tmplstr = 'autosummary/%s.rst'
try:
#.........这里部分代码省略.........
示例15: MakoBridge
class MakoBridge(TemplateBridge):
def init(self, builder, *args, **kw):
self.jinja2_fallback = BuiltinTemplateLoader()
self.jinja2_fallback.init(builder, *args, **kw)
builder.config.html_context['release_date'] = builder.config['release_date']
builder.config.html_context['site_base'] = builder.config['site_base']
self.lookup = TemplateLookup(directories=builder.config.templates_path,
#format_exceptions=True,
imports=[
"from builder import util"
]
)
if rtd:
import urllib2
template_url = builder.config['site_base'] + "/docs_base.mako"
template = urllib2.urlopen(template_url).read()
self.lookup.put_string("/rtd_base.mako", template)
def render(self, template, context):
template = template.replace(".html", ".mako")
context['prevtopic'] = context.pop('prev', None)
context['nexttopic'] = context.pop('next', None)
# RTD layout
if rtd:
# add variables if not present, such
# as if local test of READTHEDOCS variable
if 'MEDIA_URL' not in context:
context['MEDIA_URL'] = "http://media.readthedocs.org/"
if 'slug' not in context:
context['slug'] = context['project'].lower()
if 'url' not in context:
context['url'] = "/some/test/url"
if 'current_version' not in context:
context['current_version'] = "latest"
if 'name' not in context:
context['name'] = context['project'].lower()
context['rtd'] = True
context['toolbar'] = True
context['layout'] = "rtd_layout.mako"
context['base'] = "rtd_base.mako"
# pdf gen is just broken on RTD
#context['pdf_url'] = "%spdf/%s/%s/%s.pdf" % (
# context['MEDIA_URL'],
# context['slug'],
# context['current_version'],
# context['slug']
#)
# local docs layout
else:
context['rtd'] = False
context['toolbar'] = False
context['layout'] = "layout.mako"
context['base'] = "static_base.mako"
context.setdefault('_', lambda x: x)
return self.lookup.get_template(template).render_unicode(**context)
def render_string(self, template, context):
# this is used for .js, .css etc. and we don't have
# local copies of that stuff here so use the jinja render.
return self.jinja2_fallback.render_string(template, context)