Пример #1
0
def prepare(theme):
    for d in default_properties:
        if not theme.get(d):
            theme.set(d, default_properties[d])

    theme.footer_border_color = get_shade(theme.footer_color, 10)
    theme.border_color = get_shade(theme.background_color, 10)

    webfonts = list(
        set(
            theme.get(key) for key in ("heading_webfont", 'text_webfont')
            if theme.get(key)))

    theme.webfont_import = "\n".join('@import url(@import url(http://fonts.googleapis.com/css?family={0}:400,300,400italic,700&subset=latin,latin-ext);)'\
     .format(font.replace(" ", "+")) for font in webfonts)

    # move @import from css field to the top of the css file
    if theme.css:
        if "@import url" in theme.css:
            webfont_import = list(
                set(re.findall("@import url\([^\(\)]*\);", theme.css)))
            theme.webfont_import += "\n" + "\n".join(webfont_import)
            for wfimport in webfont_import:
                theme.css = theme.css.replace(wfimport, "")

        theme.css = frappe.get_jenv().from_string(theme.css)
Пример #2
0
def build_page(path):
    if not getattr(frappe.local, "path", None):
        frappe.local.path = path

    context = get_context(path)

    if context.source:
        html = frappe.render_template(context.source, context)

    elif context.template:
        if path.endswith('min.js'):
            html = frappe.get_jloader().get_source(frappe.get_jenv(),
                                                   context.template)[0]
        else:
            html = frappe.get_template(context.template).render(context)

    if '{index}' in html:
        html = html.replace('{index}', get_toc(context.route))

    if '{next}' in html:
        html = html.replace('{next}', get_next_link(context.route))

    # html = frappe.get_template(context.base_template_path).render(context)

    if can_cache(context.no_cache):
        page_cache = frappe.cache().hget("website_page", path) or {}
        page_cache[frappe.local.lang] = html
        frappe.cache().hset("website_page", path, page_cache)

    return html
Пример #3
0
def build_page(path):
	if not getattr(frappe.local, "path", None):
		frappe.local.path = path

	context = get_context(path)

	if context.source:
		html = frappe.render_template(context.source, context)

	elif context.template:
		if path.endswith('min.js'):
			html = frappe.get_jloader().get_source(frappe.get_jenv(), context.template)[0]
		else:
			html = frappe.get_template(context.template).render(context)

	if '{index}' in html:
		html = html.replace('{index}', get_toc(context.route))

	if '{next}' in html:
		html = html.replace('{next}', get_next_link(context.route))

	# html = frappe.get_template(context.base_template_path).render(context)

	if can_cache(context.no_cache):
		page_cache = frappe.cache().hget("website_page", path) or {}
		page_cache[frappe.local.lang] = html
		frappe.cache().hset("website_page", path, page_cache)

	return html
Пример #4
0
    def validate(self):
        jenv = frappe.get_jenv()
        try:
            route = resolve_route(get_path_without_slash(self.web_route))
        except Exception:
            frappe.throw(frappe.get_traceback(),
                         title=_(f"Please recheck the path: {self.web_route}"))
        if not route:
            self.validate_new_file()
            return

        route.route = get_path_without_slash(self.web_route)
        route.path = route.route
        route = build_context(route)

        if route.page_or_generator == "Generator":
            self.orignal_code = get_source_generator(route, jenv)
            self.orignal_preview_store = self.orignal_code
            self.new_preview_store = self.new_code

        elif route.page_or_generator == "Page":
            self.orignal_code = jenv.loader.get_source(jenv, route.template)[0]
            old_html = self.orignal_code
            new_html = self.new_code
            if route.template.endswith(".md"):
                old_html = frappe.utils.md_to_html(self.orignal_code)
                new_html = frappe.utils.md_to_html(self.new_code)

            self.orignal_preview_store = clean_js_css(route, old_html, jenv)
            self.new_preview_store = clean_js_css(route, old_html, jenv)

        self.set_diff()
Пример #5
0
def get_code(route):
    resolved_route = resolve_route(get_path_without_slash(route))
    jenv = frappe.get_jenv()

    if not resolved_route:
        return ""

    return get_source(resolved_route, jenv)
Пример #6
0
def setup_source(page_info):
	'''Get the HTML source of the template'''
	jenv = frappe.get_jenv()
	source = jenv.loader.get_source(jenv, page_info.template)[0]
	html = ''

	if page_info.template.endswith(('.md', '.html')):
		# extract frontmatter block if exists
		try:
			# values will be used to update page_info
			res = get_frontmatter(source)
			if res['attributes']:
				page_info.update(res['attributes'])
				source = res['body']
		except Exception:
			pass

		if page_info.template.endswith('.md'):
			source = frappe.utils.md_to_html(source)
			page_info.page_toc_html = source.toc_html

			if not page_info.show_sidebar:
				source = '<div class="from-markdown">' + source + '</div>'

	if not page_info.base_template:
		page_info.base_template = get_base_template(page_info.route)

	if 	page_info.template.endswith(('.html', '.md', )) and \
		'{%- extends' not in source and '{% extends' not in source:
		# set the source only if it contains raw content
		html = source

		# load css/js files
		js, css = '', ''

		js_path = os.path.join(page_info.basepath, (page_info.basename or 'index') + '.js')
		if os.path.exists(js_path):
			if not '{% block script %}' in html:
				with io.open(js_path, 'r', encoding = 'utf-8') as f:
					js = f.read()
				html += '\n{% block script %}<script>' + js + '\n</script>\n{% endblock %}'

		css_path = os.path.join(page_info.basepath, (page_info.basename or 'index') + '.css')
		if os.path.exists(css_path):
			if not '{% block style %}' in html:
				with io.open(css_path, 'r', encoding='utf-8') as f:
					css = f.read()
				html += '\n{% block style %}\n<style>\n' + css + '\n</style>\n{% endblock %}'

	if html:
		page_info.source = html
		page_info.base_template =  page_info.base_template or 'templates/web.html'
	else:
		page_info.source = ''

	# show table of contents
	setup_index(page_info)
Пример #7
0
 def set_vars(self):
     self.jenv = frappe.get_jenv()
     repository = frappe.get_all("Repository", [["enabled", "=", "1"]])
     if not repository:
         frappe.throw(
             "No active repositories found, contact System Manager")
     self.app = repository[0]["name"]
     self.repository = frappe.get_doc("Repository", self.app)
     self.uuid = frappe.generate_hash()
     self.repository_base_path = f"{os.getcwd()}/{frappe.local.site}/private/edit_docs/{self.uuid}"
Пример #8
0
def render_blocks(template_path, out, context):
	"""Build the template block by block from the main template."""
	env = frappe.get_jenv()
	source = frappe.local.jloader.get_source(frappe.local.jenv, template_path)[0]
	for referenced_template_path in meta.find_referenced_templates(env.parse(source)):
		if referenced_template_path:
			render_blocks(referenced_template_path, out, context)

	template = frappe.get_template(template_path)
	for block, render in template.blocks.items():
		new_context = template.new_context(context)
		out[block] = concat(render(new_context))
Пример #9
0
def render_blocks(template_path, out, context):
	"""Build the template block by block from the main template."""
	env = frappe.get_jenv()
	source = frappe.local.jloader.get_source(frappe.local.jenv, template_path)[0]
	for referenced_template_path in meta.find_referenced_templates(env.parse(source)):
		if referenced_template_path:
			render_blocks(referenced_template_path, out, context)

	template = frappe.get_template(template_path)
	for block, render in template.blocks.items():
		new_context = template.new_context(context)
		out[block] = concat(render(new_context))
Пример #10
0
	def validate(self):
		if self.standard=="Yes" and frappe.session.user != "Administrator":
			frappe.throw(frappe._("Standard Print Format cannot be updated"))

		# old_doc_type is required for clearing item cache
		self.old_doc_type = frappe.db.get_value('Print Format',
				self.name, 'doc_type')

		jenv = frappe.get_jenv()
		try:
			jenv.from_string(self.html)
		except TemplateSyntaxError:
			frappe.throw(frappe._("Syntax error in Jinja template"))
Пример #11
0
    def validate(self):
        if self.standard == "Yes" and frappe.session.user != "Administrator":
            frappe.throw(frappe._("Standard Print Format cannot be updated"))

        # old_doc_type is required for clearing item cache
        self.old_doc_type = frappe.db.get_value('Print Format', self.name,
                                                'doc_type')

        jenv = frappe.get_jenv()
        try:
            jenv.from_string(self.html)
        except TemplateSyntaxError:
            frappe.throw(frappe._("Syntax error in Jinja template"))
Пример #12
0
def get_html(doc,
             name=None,
             print_format=None,
             meta=None,
             no_letterhead=None,
             trigger_print=False):

    if isinstance(no_letterhead, basestring):
        no_letterhead = cint(no_letterhead)
    elif no_letterhead is None:
        no_letterhead = not cint(
            frappe.db.get_single_value("Print Settings", "with_letterhead"))

    if isinstance(doc, basestring) and isinstance(name, basestring):
        doc = frappe.get_doc(doc, name)

    if isinstance(doc, basestring):
        doc = frappe.get_doc(json.loads(doc))

    doc.in_print = True

    validate_print_permission(doc)

    if hasattr(doc, "before_print"):
        doc.before_print()

    if not hasattr(doc, "print_heading"): doc.print_heading = None
    if not hasattr(doc, "sub_heading"): doc.sub_heading = None

    if not meta:
        meta = frappe.get_meta(doc.doctype)

    jenv = frappe.get_jenv()
    if print_format in ("Standard", standard_format):
        template = jenv.get_template("templates/print_formats/standard.html")
    else:
        template = jenv.from_string(get_print_format(doc.doctype,
                                                     print_format))

    args = {
        "doc": doc,
        "meta": frappe.get_meta(doc.doctype),
        "layout": make_layout(doc, meta),
        "no_letterhead": no_letterhead,
        "trigger_print": cint(trigger_print),
        "letter_head": get_letter_head(doc, no_letterhead)
    }

    html = template.render(args, filters={"len": len})

    return html
Пример #13
0
def render_blocks(context):
	"""returns a dict of block name and its rendered content"""

	out = {}

	env = frappe.get_jenv()

	def _render_blocks(template_path):
		source = frappe.local.jloader.get_source(frappe.local.jenv, template_path)[0]
		for referenced_template_path in meta.find_referenced_templates(env.parse(source)):
			if referenced_template_path:
				_render_blocks(referenced_template_path)

		template = frappe.get_template(template_path)
		for block, render in template.blocks.items():
			out[block] = scrub_relative_urls(concat(render(template.new_context(context))))

	_render_blocks(context["template_path"])

	# default blocks if not found
	if "title" not in out and out.get("header"):
		out["title"] = out["header"]

	if "title" not in out:
		out["title"] = context.get("title")

	if "header" not in out and out.get("title"):
		out["header"] = out["title"]

	if not out["header"].startswith("<h"):
		out["header"] = "<h2>" + out["header"] + "</h2>"

	if "breadcrumbs" not in out:
		out["breadcrumbs"] = scrub_relative_urls(
			frappe.get_template("templates/includes/breadcrumbs.html").render(context))

	if "<!-- no-sidebar -->" in out.get("content", ""):
		out["no_sidebar"] = 1

	if "sidebar" not in out and not out.get("no_sidebar"):
		out["sidebar"] = scrub_relative_urls(
			frappe.get_template("templates/includes/sidebar.html").render(context))

	out["title"] = strip_html(out.get("title") or "")

	# remove style and script tags from blocks
	out["style"] = re.sub("</?style[^<>]*>", "", out.get("style") or "")
	out["script"] = re.sub("</?script[^<>]*>", "", out.get("script") or "")

	return out
Пример #14
0
def get_html(doc, name=None, print_format=None, meta=None,
	no_letterhead=None, trigger_print=False):

	if isinstance(no_letterhead, basestring):
		no_letterhead = cint(no_letterhead)
	elif no_letterhead is None:
		no_letterhead = not cint(frappe.db.get_single_value("Print Settings", "with_letterhead"))

	if isinstance(doc, basestring) and isinstance(name, basestring):
		doc = frappe.get_doc(doc, name)

	if isinstance(doc, basestring):
		doc = frappe.get_doc(json.loads(doc))

	doc.in_print = True

	validate_print_permission(doc)

	if hasattr(doc, "before_print"):
		doc.before_print()

	if not hasattr(doc, "print_heading"): doc.print_heading = None
	if not hasattr(doc, "sub_heading"): doc.sub_heading = None

	if not meta:
		meta = frappe.get_meta(doc.doctype)

	jenv = frappe.get_jenv()
	if print_format in ("Standard", standard_format):
		template = jenv.get_template("templates/print_formats/standard.html")
	else:
		template = jenv.from_string(get_print_format(doc.doctype,
			print_format))

	args = {
		"doc": doc,
		"meta": frappe.get_meta(doc.doctype),
		"layout": make_layout(doc, meta),
		"no_letterhead": no_letterhead,
		"trigger_print": cint(trigger_print),
		"letter_head": get_letter_head(doc, no_letterhead)
	}

	html = template.render(args, filters={"len": len})

	return html
Пример #15
0
def setup_source(page_info):
    '''Get the HTML source of the template'''
    jenv = frappe.get_jenv()
    source = jenv.loader.get_source(jenv, page_info.template)[0]
    html = ''

    if page_info.template.endswith('.md'):
        source = frappe.utils.md_to_html(source)

        if not page_info.show_sidebar:
            source = '<div class="from-markdown">' + source + '</div>'

    # if only content
    if page_info.template.endswith('.html') or page_info.template.endswith(
            '.md'):
        if ('</body>' not in source) and ('{% block' not in source):
            page_info.only_content = True
            html = '{% extends "templates/web.html" %}'
            html += '\n{% block page_content %}\n' + source + '\n{% endblock %}'
        else:
            html = source

        # load css/js files
        js, css = '', ''

        js_path = os.path.join(page_info.basepath,
                               (page_info.basename or 'index') + '.js')
        if os.path.exists(js_path):
            if not '{% block script %}' in html:
                with io.open(js_path, 'r', encoding='utf-8') as f:
                    js = f.read()
                html += '\n{% block script %}<script>' + js + '\n</script>\n{% endblock %}'

        css_path = os.path.join(page_info.basepath,
                                (page_info.basename or 'index') + '.css')
        if os.path.exists(css_path):
            if not '{% block style %}' in html:
                with io.open(css_path, 'r', encoding='utf-8') as f:
                    css = f.read()
                html += '\n{% block style %}\n<style>\n' + css + '\n</style>\n{% endblock %}'

    page_info.source = html

    # show table of contents
    setup_index(page_info)
Пример #16
0
	def validate(self):
		if (self.standard=="Yes"
			and not frappe.local.conf.get("developer_mode")
			and not (frappe.flags.in_import or frappe.flags.in_test)):

			frappe.throw(frappe._("Standard Print Format cannot be updated"))

		# old_doc_type is required for clearing item cache
		self.old_doc_type = frappe.db.get_value('Print Format',
				self.name, 'doc_type')

		if self.html:
			jenv = frappe.get_jenv()
			try:
				jenv.from_string(self.html)
			except TemplateSyntaxError, e:
				frappe.msgprint('Line {}: {}'.format(e.lineno, e.message))
				frappe.throw(frappe._("Syntax error in Jinja template"))
Пример #17
0
def add_embedded_js(doc):
    """embed all require files"""

    import re, os
    from frappe import conf

    js = doc.fields.get('__js') or ''

    # custom script
    custom = frappe.db.get_value("Custom Script", {
        "dt": doc.name,
        "script_type": "Client"
    }, "script") or ""
    js = (js + '\n' + custom).encode("utf-8")

    if "{% include" in js:
        js = frappe.get_jenv().from_string(js).render()

    doc.fields["__js"] = js
Пример #18
0
def render_blocks(context):
    """returns a dict of block name and its rendered content"""

    out = {}

    env = frappe.get_jenv()

    def _render_blocks(template_path):
        source = frappe.local.jloader.get_source(frappe.local.jenv,
                                                 template_path)[0]
        for referenced_template_path in meta.find_referenced_templates(
                env.parse(source)):
            if referenced_template_path:
                _render_blocks(referenced_template_path)

        template = frappe.get_template(template_path)
        for block, render in template.blocks.items():
            out[block] = scrub_relative_urls(
                concat(render(template.new_context(context))))

    _render_blocks(context["template_path"])

    # default blocks if not found
    if "title" not in out:
        out["title"] = context.get("title")

    if "header" not in out:
        out["header"] = out["title"]

    if not out["header"].startswith("<h"):
        out["header"] = "<h2>" + out["header"] + "</h2>"

    if "breadcrumbs" not in out:
        out["breadcrumbs"] = scrub_relative_urls(
            frappe.get_template("templates/includes/breadcrumbs.html").render(
                context))

    if "sidebar" not in out:
        out["sidebar"] = scrub_relative_urls(
            frappe.get_template("templates/includes/sidebar.html").render(
                context))

    return out
Пример #19
0
def setup_source(page_info):
    '''Get the HTML source of the template'''
    from markdown2 import markdown
    jenv = frappe.get_jenv()
    source = jenv.loader.get_source(jenv, page_info.template)[0]
    html = ''

    if page_info.template.endswith('.md'):
        source = markdown(source)

    # if only content
    if page_info.template.endswith('.html') or page_info.template.endswith(
            '.md'):
        if ('</body>' not in source) and ('{% block' not in source):
            page_info.only_content = True
            js, css = '', ''

            js_path = os.path.join(page_info.basepath,
                                   page_info.basename + '.js')
            if os.path.exists(js_path):
                js = unicode(open(js_path, 'r').read(), 'utf-8')

            css_path = os.path.join(page_info.basepath,
                                    page_info.basename + '.css')
            if os.path.exists(css_path):
                css = unicode(open(css_path, 'r').read(), 'utf-8')

            html = '{% extends "templates/web.html" %}'

            if css:
                html += '\n{% block style %}\n<style>\n' + css + '\n</style>\n{% endblock %}'

            html += '\n{% block page_content %}\n' + source + '\n{% endblock %}'

            if js:
                html += '\n{% block script %}<script>' + js + '\n</script>\n{% endblock %}'
        else:
            html = source

    page_info.source = html

    # show table of contents
    setup_index(page_info)
Пример #20
0
def setup_source(page_info):
	'''Get the HTML source of the template'''
	jenv = frappe.get_jenv()
	source = jenv.loader.get_source(jenv, page_info.template)[0]
	html = ''

	if page_info.template.endswith('.md'):
		source = frappe.utils.md_to_html(source)

		if not page_info.show_sidebar:
			source = '<div class="from-markdown">' + source + '</div>'

	# if only content
	if page_info.template.endswith('.html') or page_info.template.endswith('.md'):
		if ('</body>' not in source) and ('{% block' not in source):
			page_info.only_content = True
			html = '{% extends "templates/web.html" %}'
			html += '\n{% block page_content %}\n' + source + '\n{% endblock %}'
		else:
			html = source

		# load css/js files
		js, css = '', ''

		js_path = os.path.join(page_info.basepath, (page_info.basename or 'index') + '.js')
		if os.path.exists(js_path):
			if not '{% block script %}' in html:
				with io.open(js_path, 'r', encoding = 'utf-8') as f:
					js = f.read()
				html += '\n{% block script %}<script>' + js + '\n</script>\n{% endblock %}'

		css_path = os.path.join(page_info.basepath, (page_info.basename or 'index') + '.css')
		if os.path.exists(css_path):
			if not '{% block style %}' in html:
				with io.open(css_path, 'r', encoding='utf-8') as f:
					css = f.read()
				html += '\n{% block style %}\n<style>\n' + css + '\n</style>\n{% endblock %}'

	page_info.source = html

	# show table of contents
	setup_index(page_info)
Пример #21
0
	def validate(self):
		if (self.standard=="Yes"
			and not frappe.local.conf.get("developer_mode")
			and not (frappe.flags.in_import or frappe.flags.in_test)):

			frappe.throw(frappe._("Standard Print Format cannot be updated"))

		# old_doc_type is required for clearing item cache
		self.old_doc_type = frappe.db.get_value('Print Format',
				self.name, 'doc_type')

		self.extract_images()

		if self.html:
			jenv = frappe.get_jenv()
			try:
				jenv.from_string(self.html)
			except TemplateSyntaxError, e:
				frappe.msgprint('Line {}: {}'.format(e.lineno, e.message))
				frappe.throw(frappe._("Syntax error in Jinja template"))
Пример #22
0
def setup_source(page_info):
	'''Get the HTML source of the template'''
	from markdown2 import markdown
	jenv = frappe.get_jenv()
	source = jenv.loader.get_source(jenv, page_info.template)[0]
	html = ''

	if page_info.template.endswith('.md'):
		source = markdown(source)

	# if only content
	if page_info.template.endswith('.html') or page_info.template.endswith('.md'):
		if ('</body>' not in source) and ('{% block' not in source):
			page_info.only_content = True
			js, css = '', ''

			js_path = os.path.join(page_info.basepath, page_info.basename + '.js')
			if os.path.exists(js_path):
				js = unicode(open(js_path, 'r').read(), 'utf-8')

			css_path = os.path.join(page_info.basepath, page_info.basename + '.css')
			if os.path.exists(css_path):
				css = unicode(open(css_path, 'r').read(), 'utf-8')

			html = '{% extends "templates/web.html" %}'

			if css:
				html += '\n{% block style %}\n<style>\n' + css + '\n</style>\n{% endblock %}'

			html += '\n{% block page_content %}\n' + source + '\n{% endblock %}'

			if js:
				html += '\n{% block script %}<script>' + js + '\n</script>\n{% endblock %}'
		else:
			html = source

	page_info.source = html

	# show table of contents
	setup_index(page_info)
Пример #23
0
def preview(content, path, attachments="{}"):

    raw_edited_content = content

    attachments = json.loads(attachments)

    for attachment in attachments:
        if attachment.get("save_path"):
            content = content.replace(attachment.get("save_path"),
                                      attachment.get("file_url"))

    try:
        resolved_route = resolve_route(get_path_without_slash(path))
    except Exception:
        frappe.throw(frappe.get_traceback(),
                     title=_(f"Please recheck the path: {path}"))

    if not resolved_route:
        return {
            "diff": diff("", content),
            "html": frappe.utils.md_to_html(content)
        }

    resolved_route.route = get_path_without_slash(path)
    resolved_route.path = resolved_route.route

    resolved_route = build_context(resolved_route)

    jenv = frappe.get_jenv()

    old_code_md = get_source(resolved_route, jenv)

    if resolved_route.page_or_generator == "Page":
        if resolved_route.template.endswith(".md"):
            content = frappe.utils.md_to_html(content)
            old_code = frappe.utils.md_to_html(old_code_md)
        content = clean_js_css(resolved_route, content, jenv)

    return {"diff": diff(old_code_md, raw_edited_content), "html": content}
Пример #24
0
def render_blocks(context):
    """returns a dict of block name and its rendered content"""

    out = {}

    env = frappe.get_jenv()

    def _render_blocks(template_path):
        source = frappe.local.jloader.get_source(frappe.local.jenv,
                                                 template_path)[0]
        for referenced_template_path in meta.find_referenced_templates(
                env.parse(source)):
            if referenced_template_path:
                _render_blocks(referenced_template_path)

        template = frappe.get_template(template_path)
        for block, render in template.blocks.items():
            out[block] = scrub_relative_urls(
                concat(render(template.new_context(context))))

    _render_blocks(context["template"])

    # default blocks if not found
    if "title" not in out and out.get("header"):
        out["title"] = out["header"]

    if "title" not in out:
        out["title"] = context.get("title")

    if "header" not in out and out.get("title"):
        out["header"] = out["title"]

    if out.get("header") and not out["header"].startswith("<h"):
        out["header"] = "<h2>" + out["header"] + "</h2>"

    if "breadcrumbs" not in out:
        out["breadcrumbs"] = scrub_relative_urls(
            frappe.get_template("templates/includes/breadcrumbs.html").render(
                context))

    if "meta_block" not in out:
        out["meta_block"] = frappe.get_template(
            "templates/includes/meta_block.html").render(context)

    out["no_sidebar"] = context.get("no_sidebar", 0)

    if "<!-- no-sidebar -->" in out.get("content", ""):
        out["no_sidebar"] = 1

    if "<!-- title:" in out.get("content", ""):
        out["title"] = re.findall('<!-- title:([^>]*) -->',
                                  out.get("content"))[0].strip()

    if "{index}" in out.get("content", "") and context.get("children"):
        html = frappe.get_template(
            "templates/includes/static_index.html").render(
                {"items": context["children"]})
        out["content"] = out["content"].replace("{index}", html)

    if "{next}" in out.get("content", ""):
        next_item = context.doc.get_next()
        if next_item:
            if next_item.name[0] != "/": next_item.name = "/" + next_item.name
            html = '''<p><br><a href="{name}" class="btn btn-primary">
				{title} <i class="icon-chevron-right"></i></a>
			</p>'''.format(**next_item)
            out["content"] = out["content"].replace("{next}", html)

    if "sidebar" not in out and not out.get("no_sidebar"):
        out["sidebar"] = scrub_relative_urls(
            frappe.get_template("templates/includes/sidebar.html").render(
                context))

    out["title"] = strip_html(out.get("title") or "")

    # remove style and script tags from blocks
    out["style"] = re.sub("</?style[^<>]*>", "", out.get("style") or "")
    out["script"] = re.sub("</?script[^<>]*>", "", out.get("script") or "")

    return out
Пример #25
0
def get_html(doc,
             name=None,
             print_format=None,
             meta=None,
             no_letterhead=None,
             trigger_print=False):

    print_settings = frappe.db.get_singles_dict("Print Settings")

    if isinstance(no_letterhead, basestring):
        no_letterhead = cint(no_letterhead)

    elif no_letterhead is None:
        no_letterhead = not cint(print_settings.with_letterhead)

    doc.flags.in_print = True

    if not frappe.flags.ignore_print_permissions:
        validate_print_permission(doc)

    if doc.meta.is_submittable:
        if doc.docstatus == 0 and not cint(
                print_settings.allow_print_for_draft):
            frappe.throw(_("Not allowed to print draft documents"),
                         frappe.PermissionError)

        if doc.docstatus == 2 and not cint(
                print_settings.allow_print_for_cancelled):
            frappe.throw(_("Not allowed to print cancelled documents"),
                         frappe.PermissionError)

    if hasattr(doc, "before_print"):
        doc.before_print()

    if not hasattr(doc, "print_heading"): doc.print_heading = None
    if not hasattr(doc, "sub_heading"): doc.sub_heading = None

    if not meta:
        meta = frappe.get_meta(doc.doctype)

    jenv = frappe.get_jenv()
    format_data, format_data_map = [], {}

    # determine template
    if print_format:
        doc._show_section_headings = print_format.show_section_headings
        doc._line_breaks = print_format.line_breaks
        doc._align_labels_left = print_format.align_labels_left

        def get_template_from_string():
            return jenv.from_string(get_print_format(doc.doctype,
                                                     print_format))

        if print_format.custom_format:
            template = get_template_from_string()

        elif print_format.format_data:
            # set format data
            format_data = json.loads(print_format.format_data)
            for df in format_data:
                format_data_map[df.get("fieldname")] = df
                if "visible_columns" in df:
                    for _df in df.get("visible_columns"):
                        format_data_map[_df.get("fieldname")] = _df

            doc.format_data_map = format_data_map

            template = "standard"

        elif print_format.standard == "Yes":
            template = get_template_from_string()

        else:
            # fallback
            template = "standard"

    else:
        template = "standard"

    if template == "standard":
        template = jenv.get_template(standard_format)

    letter_head = frappe._dict(get_letter_head(doc, no_letterhead) or {})

    if letter_head.content:
        letter_head.content = frappe.utils.jinja.render_template(
            letter_head.content, {"doc": doc.as_dict()})

    if letter_head.footer:
        letter_head.footer = frappe.utils.jinja.render_template(
            letter_head.footer, {"doc": doc.as_dict()})

    convert_markdown(doc, meta)

    args = {
        "doc": doc,
        "meta": frappe.get_meta(doc.doctype),
        "layout": make_layout(doc, meta, format_data),
        "no_letterhead": no_letterhead,
        "trigger_print": cint(trigger_print),
        "letter_head": letter_head.content,
        "footer": letter_head.footer,
        "print_settings": frappe.get_doc("Print Settings")
    }

    html = template.render(args, filters={"len": len})

    if cint(trigger_print):
        html += trigger_print_script

    return html
Пример #26
0
	def render_jinja(content):
		if "{% include" in content:
			content = frappe.get_jenv().from_string(content).render()
		return content
Пример #27
0
 def get_raw_template(self):
     return frappe.get_jloader().get_source(frappe.get_jenv(),
                                            self.context.template)[0]
Пример #28
0
def get_html(doc, name=None, print_format=None, meta=None,
	no_letterhead=None, trigger_print=False):

	print_settings = frappe.db.get_singles_dict("Print Settings")

	if isinstance(no_letterhead, string_types):
		no_letterhead = cint(no_letterhead)

	elif no_letterhead is None:
		no_letterhead = not cint(print_settings.with_letterhead)

	doc.flags.in_print = True

	if not frappe.flags.ignore_print_permissions:
		validate_print_permission(doc)

	if doc.meta.is_submittable:
		if doc.docstatus==0 and not cint(print_settings.allow_print_for_draft):
			frappe.throw(_("Not allowed to print draft documents"), frappe.PermissionError)

		if doc.docstatus==2 and not cint(print_settings.allow_print_for_cancelled):
			frappe.throw(_("Not allowed to print cancelled documents"), frappe.PermissionError)

	if hasattr(doc, "before_print"):
		doc.before_print()

	if not hasattr(doc, "print_heading"): doc.print_heading = None
	if not hasattr(doc, "sub_heading"): doc.sub_heading = None

	if not meta:
		meta = frappe.get_meta(doc.doctype)

	jenv = frappe.get_jenv()
	format_data, format_data_map = [], {}

	# determine template
	if print_format:
		doc._show_section_headings = print_format.show_section_headings
		doc._line_breaks = print_format.line_breaks
		doc._align_labels_right = print_format.align_labels_right

		def get_template_from_string():
			return jenv.from_string(get_print_format(doc.doctype,
				print_format))

		if print_format.custom_format:
			template = get_template_from_string()

		elif print_format.format_data:
			# set format data
			format_data = json.loads(print_format.format_data)
			for df in format_data:
				format_data_map[df.get("fieldname")] = df
				if "visible_columns" in df:
					for _df in df.get("visible_columns"):
						format_data_map[_df.get("fieldname")] = _df

			doc.format_data_map = format_data_map

			template = "standard"

		elif print_format.standard=="Yes":
			template = get_template_from_string()

		else:
			# fallback
			template = "standard"

	else:
		template = "standard"


	if template == "standard":
		template = jenv.get_template(standard_format)

	letter_head = frappe._dict(get_letter_head(doc, no_letterhead) or {})

	if letter_head.content:
		letter_head.content = frappe.utils.jinja.render_template(letter_head.content, {"doc": doc.as_dict()})

	if letter_head.footer:
		letter_head.footer = frappe.utils.jinja.render_template(letter_head.footer, {"doc": doc.as_dict()})

	convert_markdown(doc, meta)

	args = {
		"doc": doc,
		"meta": frappe.get_meta(doc.doctype),
		"layout": make_layout(doc, meta, format_data),
		"no_letterhead": no_letterhead,
		"trigger_print": cint(trigger_print),
		"letter_head": letter_head.content,
		"footer": letter_head.footer,
		"print_settings": frappe.get_doc("Print Settings")
	}

	html = template.render(args, filters={"len": len})

	if cint(trigger_print):
		html += trigger_print_script

	return html
Пример #29
0
def render_blocks(context):
	"""returns a dict of block name and its rendered content"""

	out = {}

	env = frappe.get_jenv()

	def _render_blocks(template_path):
		source = frappe.local.jloader.get_source(frappe.local.jenv, template_path)[0]
		for referenced_template_path in meta.find_referenced_templates(env.parse(source)):
			if referenced_template_path:
				_render_blocks(referenced_template_path)

		template = frappe.get_template(template_path)
		for block, render in template.blocks.items():
			out[block] = scrub_relative_urls(concat(render(template.new_context(context))))

	_render_blocks(context["template"])

	# default blocks if not found
	if "title" not in out and out.get("header"):
		out["title"] = out["header"]

	if "title" not in out:
		out["title"] = context.get("title")

	if "header" not in out and out.get("title"):
		out["header"] = out["title"]

	if out.get("header") and not out["header"].startswith("<h"):
		out["header"] = "<h2>" + out["header"] + "</h2>"

	if "breadcrumbs" not in out:
		out["breadcrumbs"] = scrub_relative_urls(
			frappe.get_template("templates/includes/breadcrumbs.html").render(context))

	if "meta_block" not in out:
		out["meta_block"] = frappe.get_template("templates/includes/meta_block.html").render(context)


	out["no_sidebar"] = context.get("no_sidebar", 0)

	if "<!-- no-sidebar -->" in out.get("content", ""):
		out["no_sidebar"] = 1

	if "<!-- title:" in out.get("content", ""):
		out["title"] = re.findall('<!-- title:([^>]*) -->', out.get("content"))[0].strip()

	if "{index}" in out.get("content", "") and context.get("children"):
		html = frappe.get_template("templates/includes/static_index.html").render({
				"items": context["children"]})
		out["content"] = out["content"].replace("{index}", html)

	if "{next}" in out.get("content", ""):
		next_item = context.doc.get_next()
		if next_item:
			if next_item.name[0]!="/": next_item.name = "/" + next_item.name
			html = '''<p><br><a href="{name}" class="btn btn-primary">
				{title} <i class="icon-chevron-right"></i></a>
			</p>'''.format(**next_item)
			out["content"] = out["content"].replace("{next}", html)

	if "sidebar" not in out and not out.get("no_sidebar"):
		out["sidebar"] = scrub_relative_urls(
			frappe.get_template("templates/includes/sidebar.html").render(context))

	out["title"] = strip_html(out.get("title") or "")

	# remove style and script tags from blocks
	out["style"] = re.sub("</?style[^<>]*>", "", out.get("style") or "")
	out["script"] = re.sub("</?script[^<>]*>", "", out.get("script") or "")

	return out
Пример #30
0
 def render(doc, format='Invoice Receiving Email'):
     jenv = frappe.get_jenv()
     template = jenv.from_string(
         get_print_format('Invoice Receiving Email Tool', format))
     return template.render(**doc)
Пример #31
0
 def render(self, row):
     jenv = frappe.get_jenv()
     template = jenv.from_string(
         get_print_format('Quotation Tool', 'Quotation Email'))
     return template.render(**row)
Пример #32
0
def get_html(doc, name=None, print_format=None, meta=None,
	no_letterhead=None, trigger_print=False):

	if isinstance(no_letterhead, basestring):
		no_letterhead = cint(no_letterhead)
	elif no_letterhead is None:
		no_letterhead = not cint(frappe.db.get_single_value("Print Settings", "with_letterhead"))

	if isinstance(doc, basestring) and isinstance(name, basestring):
		doc = frappe.get_doc(doc, name)

	if isinstance(doc, basestring):
		doc = frappe.get_doc(json.loads(doc))

	doc.flags.in_print = True

	if not frappe.flags.ignore_print_permissions:
		validate_print_permission(doc)

	if hasattr(doc, "before_print"):
		doc.before_print()

	if not hasattr(doc, "print_heading"): doc.print_heading = None
	if not hasattr(doc, "sub_heading"): doc.sub_heading = None

	if not meta:
		meta = frappe.get_meta(doc.doctype)

	jenv = frappe.get_jenv()
	format_data, format_data_map = [], {}

	# determine template
	if print_format in ("Standard", standard_format):
		template = "standard"
	else:
		print_format = frappe.get_doc("Print Format", print_format)
		if print_format.format_data:
			# set format data
			format_data = json.loads(print_format.format_data)
			for df in format_data:
				format_data_map[df.get("fieldname")] = df
				if "visible_columns" in df:
					for _df in df.get("visible_columns"):
						format_data_map[_df.get("fieldname")] = _df

			doc.format_data_map = format_data_map

			template = "standard"
		else:
			template = jenv.from_string(get_print_format(doc.doctype,
				print_format))

	if template == "standard":
		template = jenv.get_template("templates/print_formats/standard.html")

	args = {
		"doc": doc,
		"meta": frappe.get_meta(doc.doctype),
		"layout": make_layout(doc, meta, format_data),
		"no_letterhead": no_letterhead,
		"trigger_print": cint(trigger_print),
		"letter_head": get_letter_head(doc, no_letterhead)
	}

	html = template.render(args, filters={"len": len})

	return html
Пример #33
0
def get_html(doc,
             name=None,
             print_format=None,
             meta=None,
             no_letterhead=None,
             trigger_print=False):

    if isinstance(no_letterhead, basestring):
        no_letterhead = cint(no_letterhead)
    elif no_letterhead is None:
        no_letterhead = not cint(
            frappe.db.get_single_value("Print Settings", "with_letterhead"))

    doc.flags.in_print = True

    if not frappe.flags.ignore_print_permissions:
        validate_print_permission(doc)

    if hasattr(doc, "before_print"):
        doc.before_print()

    if not hasattr(doc, "print_heading"): doc.print_heading = None
    if not hasattr(doc, "sub_heading"): doc.sub_heading = None

    if not meta:
        meta = frappe.get_meta(doc.doctype)

    jenv = frappe.get_jenv()
    format_data, format_data_map = [], {}

    # determine template
    if print_format:
        if print_format.standard == "Yes" or print_format.custom_format:
            template = jenv.from_string(
                get_print_format(doc.doctype, print_format))

        elif print_format.format_data:
            # set format data
            format_data = json.loads(print_format.format_data)
            for df in format_data:
                format_data_map[df.get("fieldname")] = df
                if "visible_columns" in df:
                    for _df in df.get("visible_columns"):
                        format_data_map[_df.get("fieldname")] = _df

            doc.format_data_map = format_data_map

            template = "standard"

        else:
            # fallback
            template = "standard"

    else:
        template = "standard"

    if template == "standard":
        template = jenv.get_template(standard_format)

    letter_head = frappe._dict(get_letter_head(doc, no_letterhead) or {})
    args = {
        "doc": doc,
        "meta": frappe.get_meta(doc.doctype),
        "layout": make_layout(doc, meta, format_data),
        "no_letterhead": no_letterhead,
        "trigger_print": cint(trigger_print),
        "letter_head": letter_head.content,
        "footer": letter_head.footer,
        "print_settings": frappe.get_doc("Print Settings")
    }

    html = template.render(args, filters={"len": len})

    if cint(trigger_print):
        html += trigger_print_script

    return html
Пример #34
0
def get_html(doc, name=None, print_format=None, meta=None,
	no_letterhead=None, trigger_print=False):

	if isinstance(no_letterhead, basestring):
		no_letterhead = cint(no_letterhead)
	elif no_letterhead is None:
		no_letterhead = not cint(frappe.db.get_single_value("Print Settings", "with_letterhead"))

	doc.flags.in_print = True

	if not frappe.flags.ignore_print_permissions:
		validate_print_permission(doc)

	if hasattr(doc, "before_print"):
		doc.before_print()

	if not hasattr(doc, "print_heading"): doc.print_heading = None
	if not hasattr(doc, "sub_heading"): doc.sub_heading = None

	if not meta:
		meta = frappe.get_meta(doc.doctype)

	jenv = frappe.get_jenv()
	format_data, format_data_map = [], {}

	# determine template
	if print_format:
		if print_format.standard=="Yes" or print_format.custom_format:
			template = jenv.from_string(get_print_format(doc.doctype,
				print_format))

		elif print_format.format_data:
			# set format data
			format_data = json.loads(print_format.format_data)
			for df in format_data:
				format_data_map[df.get("fieldname")] = df
				if "visible_columns" in df:
					for _df in df.get("visible_columns"):
						format_data_map[_df.get("fieldname")] = _df

			doc.format_data_map = format_data_map

			template = "standard"

		else:
			# fallback
			template = "standard"

	else:
		template = "standard"


	if template == "standard":
		template = jenv.get_template(standard_format)

	letter_head = frappe._dict(get_letter_head(doc, no_letterhead) or {})
	args = {
		"doc": doc,
		"meta": frappe.get_meta(doc.doctype),
		"layout": make_layout(doc, meta, format_data),
		"no_letterhead": no_letterhead,
		"trigger_print": cint(trigger_print),
		"letter_head": letter_head.content,
		"footer": letter_head.footer,
		"print_settings": frappe.get_doc("Print Settings")
	}

	html = template.render(args, filters={"len": len})

	if cint(trigger_print):
		html += trigger_print_script

	return html
Пример #35
0
def get_html(doc, name=None, print_format=None, meta=None,
	no_letterhead=None, trigger_print=False):

	if isinstance(no_letterhead, basestring):
		no_letterhead = cint(no_letterhead)
	elif no_letterhead is None:
		no_letterhead = not cint(frappe.db.get_single_value("Print Settings", "with_letterhead"))

	if isinstance(doc, basestring) and isinstance(name, basestring):
		doc = frappe.get_doc(doc, name)

	if isinstance(doc, basestring):
		doc = frappe.get_doc(json.loads(doc))

	doc.flags.in_print = True

	if not frappe.flags.ignore_print_permissions:
		validate_print_permission(doc)

	if hasattr(doc, "before_print"):
		doc.before_print()

	if not hasattr(doc, "print_heading"): doc.print_heading = None
	if not hasattr(doc, "sub_heading"): doc.sub_heading = None

	if not meta:
		meta = frappe.get_meta(doc.doctype)

	jenv = frappe.get_jenv()
	format_data, format_data_map = [], {}

	# determine template
	if print_format in ("Standard", standard_format):
		template = "standard"
	else:
		print_format = frappe.get_doc("Print Format", print_format)
		if print_format.format_data:
			# set format data
			format_data = json.loads(print_format.format_data)
			for df in format_data:
				format_data_map[df.get("fieldname")] = df
				if "visible_columns" in df:
					for _df in df.get("visible_columns"):
						format_data_map[_df.get("fieldname")] = _df

			doc.format_data_map = format_data_map

			template = "standard"
		else:
			template = jenv.from_string(get_print_format(doc.doctype,
				print_format))

	if template == "standard":
		template = jenv.get_template("templates/print_formats/standard.html")

	args = {
		"doc": doc,
		"meta": frappe.get_meta(doc.doctype),
		"layout": make_layout(doc, meta, format_data),
		"no_letterhead": no_letterhead,
		"trigger_print": cint(trigger_print),
		"letter_head": get_letter_head(doc, no_letterhead)
	}

	html = template.render(args, filters={"len": len})

	return html