def query(): error = None if request.method == 'GET': if not request.args.get('url'): error = 'No URL' elif not request.args.get('query_string'): error = 'No query string' else: # url = request.args.get('url') # query_string = request.args.get('query_string') # flash('query!!') # html = rst.urlopen(url).read() with open('test.html') as reader: html = reader.read() soup = BeautifulSoup(html, 'html.parser') results = soup.find_all('title') mark='QUERY' + 100*'-' highlight_result_lst = [] for result in results: # hltag = soup.new_tag(mark) # hltag.attrs.setdefault('class', mark) # result.wrap(hltag) # classes = result.attrs.setdefault('class', mark) # if isinstance(classes, list) and mark not in classes: # classes.append(mark) # elif not isinstance(classes, list) and classes!=mark: # classes = mark highlight_result = highlight(BeautifulSoup(str(result), 'html.parser').prettify(), HtmlLexer(), HtmlFormatter()) print(highlight_result) highlight_result = highlight_result.partition('<div class="highlight"><pre>')[2] print(highlight_result) print(highlight_result.rpartition('</pre></div>')) highlight_result = highlight_result.rpartition('</pre></div>')[0] # highlight_result = BeautifulSoup(highlight_result, 'html.parser').prettify() print(highlight_result) highlight_result_lst.append(highlight_result) html = soup.prettify() html_lexer = HtmlLexer() namefilter = NameHighlightFilter(names=[mark]) html_lexer.add_filter(namefilter) highlight_html = highlight(html,html_lexer, HtmlFormatter()) print() print() print() print() print() print(highlight_html) for highlight_result in highlight_result_lst: highlight_html = highlight_html.replace(highlight_result, '222'+highlight_result+'222') return render_template('query.html', html=Markup(highlight_html)) return render_template('query.html', error=error)
def view_source(self, req, resp, url): """ View the highlighted source (from `action_view`). """ content_type = resp.content_type if content_type.startswith('application/xml'): lexer = XmlLexer() elif content_type == 'text/html': lexer = HtmlLexer() else: ## FIXME: what then? lexer = HtmlLexer() text = pygments_highlight( resp.body, lexer, HtmlFormatter(full=True, linenos=True, lineanchors='code')) return Response(text)
def highlight(html_code): """Highlights the given code (for use in the template)""" if isinstance(html_code, _Element): html_code = tostring(html_code) return html( pygments_highlight(html_code, HtmlLexer(), HtmlFormatter(noclasses=True)))
def example(example_name): form, form_code = get_form(example_name) template_obj, template_code = get_template(example_name) rendered = template_obj.render( template.Context({ 'form': form(), 'MEDIA_URL': settings.MEDIA_URL })) if highlight: formatter = HtmlFormatter() form_code = highlight(form_code, PythonLexer(), formatter) template_code = highlight(template_code, HtmlDjangoLexer(), formatter) rendered_code = highlight(rendered, HtmlLexer(), formatter) else: form_code = u'<pre>%s</pre>' % form_code tpl = u'<pre><form action="" method="POST">%s</form></pre>' template_code = tpl % template_code rendered_code = tpl % escape(rendered) return { 'name': example_name, 'form_code': mark_safe(form_code), 'template': mark_safe(template_code), 'rendered_code': mark_safe(rendered_code), 'rendered': rendered, }
def migrate_description(obj, verbose, html_log): h = HTML2Text() h.unicode_snob = True result = h.handle(unicode(obj.description)) if verbose: click.echo(click.style('\n' + ' ' * 80, bg='cyan', fg='black')) click.echo(click.style(repr(obj), fg='cyan')) click.echo( _deleted( highlight(unicode(obj.description), HtmlLexer(), Terminal256Formatter()))) click.echo(_added(result)) if re.search(r'</\w+>', result): click.echo( click.style('[FAIL] ', fg='yellow', bold=True) + click.style(repr(obj), fg='cyan')) click.echo(click.style(obj.description, fg='yellow', dim=True)) choice = click.prompt( "What do you want to do? [s = skip / c = change anyway / q = quit]" ) if choice == 's': return elif choice == 'q': sys.exit(1) else: _new_row(html_log, obj, result) else: _new_row(html_log, obj, result) obj.description = result
def pygmentize(text, language): """Pygmentizes the given block of text.""" try: lexer = get_lexer_by_name(language) except: lexer = HtmlLexer() return mark_safe(highlight(text, lexer, HtmlFormatter()))
def migrate_description(obj, verbose, html_log, use_pandoc=False): input_html = re.sub(r'^\r?\n$', '<br>', unicode(obj.description)) result, convert_to_markdown = purify_html(input_html, obj) if convert_to_markdown: if use_pandoc: result = convert_using_pandoc(result) else: result = convert_using_html2text(result) if verbose: click.echo(click.style('\n' + ' ' * 80, bg='cyan', fg='black')) click.echo(click.style(repr(obj), fg='cyan')) click.echo(_deleted(highlight(unicode(input_html), HtmlLexer(), Terminal256Formatter()))) click.echo(_added(result)) if convert_to_markdown and re.search(r'</\w+>', result): click.echo(click.style('[FAIL] ', fg='yellow', bold=True) + click.style(repr(obj), fg='cyan')) click.echo(click.style(obj.description, fg='red', dim=True)) click.echo(click.style(result, fg='green', dim=True)) choice = click.prompt("What do you want to do? [s = skip / c = change anyway / q = quit]") if choice == 's': return elif choice == 'q': sys.exit(1) else: _new_row(html_log, obj, result) else: _new_row(html_log, obj, result) obj.description = result
def template(template_id): """ The view where we display the result in syntax-highlighted HTML and CSS """ template = Template.query.filter(Template.id == long(template_id)).first() if not template: return "The requested template doesn't exist", 404 hashtml = len(template.html.strip()) > 0 cssperma = template.css_url pygmented_css_link = None if cssperma: pygmented_css_link = highlight( '<link rel="stylesheet" type="text/css" href="%s">' % cssperma, CssLexer(), HtmlFormatter(style='bw', linenos='table')) return render_template( 'saved_template.html', template=template, pygmented_css_link_code=pygmented_css_link, pygmented_html_code=highlight( template.html, HtmlLexer(), HtmlFormatter(style='bw', linenos='table')), pygmented_css_code=highlight( template.css, CssLexer(), HtmlFormatter(style='bw', linenos='table')), pygments_style=HtmlFormatter(style='bw').get_style_defs('.highlight'), hashtml=hashtml, )
def run(self): """Runs the command.""" data = self.distribution.get_long_description() stream = io.StringIO() # TODO: this will only work for RST!!! render = self.get_renderer() markup = render(data, stream=stream) for line in stream.getvalue().splitlines(): if line.startswith("<string>"): line = line[8:] self.warn(line) if markup is None: self.warn("Invalid markup which will not be rendered on PyPI.") if self.preview: with NamedTemporaryFile( prefix='render_readme_', suffix='.html', delete=False, ) as f: print('Writing readme to {0}'.format(f.name)) f.write(markup.encode('utf-8')) webbrowser.open('file://' + f.name.replace('\\', '/')) else: if not self.no_color: lexer = HtmlLexer() formatter = Terminal256Formatter(style=self.style) markup = highlight(markup, lexer, formatter) sys.stdout.write(markup)
def run_test(chapter_num=None, section_num=None, test_index=None, test_id=None): if test_id is None: try: chapter, sections, _ = chapters[chapter_num - 1] title, url, tests = sections[section_num - 1] test = tests[test_index - 1] previous_index = test_index - 1 next_index = test_index + 1 if test_index < len(tests) else None except IndexError: abort(404) else: test = dict(test_id=test_id) from pygments import highlight from pygments.lexers import HtmlLexer from pygments.formatters import HtmlFormatter filename = safe_join(suite_directory, test['test_id'] + '.htm') with open(filename, 'rb') as fd: source = fd.read().decode('utf8') formatter = HtmlFormatter(linenos='inline') source = highlight(source, HtmlLexer(), formatter) css = formatter.get_style_defs('.highlight') return render_template('run_test.html', **locals())
def viewSrc(self): html = self.currentBrowser().page().mainFrame().toHtml().toUtf8() try: url = str(self.lineEdit.text()) self.addNewTab(url=QtCore.QUrl("view.source:%s" %url)) html2 = highlight(str(html), HtmlLexer(), HtmlFormatter(linenos=True,full=True)) self.currentBrowser().setHtml("<title>view.source:%s</title>%s" % (url,html2)) except ImportError, e: self.currentBrowser().setHtml(str(html))
def build(self): return CodeInput(lexer = HtmlLexer()) return Button(text = "Knopka!", font_size = 30, on_press = self.btn_press, background_color = [1.48, .79, .4, 1], background_normal = '' )
def add_pygment(matchobj): #string = matchobj.group(0) lang = matchobj.group(2) text = matchobj.group(4) #print text, lang try: lexer = get_lexer_by_name(lang, encoding='UTF-8') except: lexer = HtmlLexer() return highlight(text, lexer, HtmlFormatter())
def render(self, context): lang = 'python' if len(self.vlist) > 0: lang = resolve_variable(self.vlist[0], context) try: lexer = get_lexer_by_name(lang, encoding='UTF-8') except: lexer = HtmlLexer() return highlight(self.nodelist.render(context), lexer, HtmlFormatter())
def __render(self): if SHOW_RENDERED_HTML: yield string_representation(cleaned_beautifulsoup_copy(self)) yield u"<hr/>" yield string_representation(highlight( self.prettify(), HtmlLexer(), HtmlFormatter(noclasses=True), )) yield u"<hr/>"
def pygmentize(text, format): """Returns respective HTML snippet of a source code aimed to be highlighted.""" if format == "n3" or format == "turtle" or format == "nt" or format == "nquads": lexer = Notation3Lexer() elif format == "rdfa" or format == "microdata": lexer = HtmlLexer() elif format == "pretty-xml" or format == "xml" or format == "trix": lexer = XmlLexer() elif format == "rdf-json" or format == "rdf-json-pretty" or format == "json-ld": lexer = JsonLexer() else: lexer = guess_lexer(text) return highlight(text, lexer, HtmlFormatter())
def _highlight(self, html_code): from IPython.display import HTML formatter = HtmlFormatter(linenos=False, cssclass="source") html_highlight = highlight(html_code, HtmlLexer(), formatter) css_style = formatter.get_style_defs() html_template = """<style> {} </style> {} """.format(css_style, html_highlight) return HTML(html_template)
def highlight_html_filter(source, linenos=False, linenostart=1, identifier=None): """ Filter function to highlight HTML source with Pygments and some options. Line breaks are replaced with character ``↩`` to improve readability. This does not embed Pygments styles as inline styles, you will need to load these stylesheets from your document. Example: {{ "<p>Foobar</p>"|highlight_html }} {{ "<p>Foobar</p>"|highlight_html(linenos=True) }} {{ "<p>Foobar</p>"|highlight_html(linenos=True, linenostart=42) }} {{ "<p>Foobar</p>"|highlight_html(linenos=True, identifier="foo") }} Arguments: source (string): Source string to highlight. Keyword Arguments: linenos (bool): To enable or disable line numbers. Disabled by default. linenostart (int): To start line numbers from a specific number. Default to 1. identifier (string): An identifier string to prefix line anchors. So with ``id="foo"``, line 42 anchor will be named ``foo-42``. You must fill it to enable line anchor. Returns: string: HTML for highlighted source. """ if linenos: linenos = "table" opts = { "cssclass": "highlight", "linenos": linenos, "linenostart": linenostart, "wrapcode": True, } if linenos and identifier: opts.update({ "lineanchors": identifier, "anchorlinenos": True, }) return highlight( source, HtmlLexer(), HtmlFormatter(**opts) )
def _get_lexer(codesyntax): if codesyntax in ('cpp', 'javascript'): return JavascriptLexer() elif codesyntax == 'python': return PythonLexer() elif codesyntax == 'xml' or codesyntax == 'html': return HtmlLexer() elif codesyntax == 'css': return CssLexer() elif codesyntax == 'sql': return SqlLexer() elif codesyntax: raise NotImplementedError(codesyntax) else: return TextLexer()
def open_raw(self): r = requests.get(self.post.url) allowed_headers = ['text/html', 'text/plain', 'application/json'] if not r.headers['content-type'].split(';')[0] in allowed_headers: self.renderarea.original_widget = urwid.Filler( urwid.Text( ('inactive', 'could not load\ncontent-type {}'.format( r.headers['content-type'])), align='center')) return content = highlight(r.text, HtmlLexer(), TerminalFormatter()) content = urwidify_content(content) adsp = urwid.ListBox(content) self.renderarea.original_widget = urwid.Filler(adsp, height=('relative', 100), valign='top')
def __repr_html(self): # string addition is slow (and makes copies) yield u"<table>" yield u"<tr><th>Index</th><th>Render</th><th>source</th></tr>" for num, item in enumerate(self): yield u"<tr>" yield u"<td>" yield str(num) yield u"</td>" yield u"<td>" yield string_representation(cleaned_beautifulsoup_copy(item)) yield u"</td>" yield u"<td>" yield highlight( item.prettify(), HtmlLexer(), HtmlFormatter(noclasses=True), ) yield u"</td>" yield u"</tr>" yield u"</table>"
def pigmentize(text): """searches for <span></span> and replace with HTML pigmented code supported languages: python ; html ; css ; emacs ; bash ; hexdump ; DjangoLexer""" start_code = text.find('<pre>') + 5 end_code = text.find('</pre') code = text[start_code:end_code] if code[0:5] == 'python': text.replace('<div class="highlight"><pre>' + highlight(code, PythonLexer(), HtmlFormatter()) + '</pre></div>') if code[0:4] == 'html': text.replace('<div class="highlight"><pre>' + highlight(code, HtmlLexer(), HtmlFormatter()) + '</pre></div>') if code[0:3] == 'css': text.replace('<div class="highlight"><pre>' + highlight(code, CssLexer(), HtmlFormatter()) + '</pre></div>') if code[0:5] == 'emac': text.replace('<div class="highlight"><pre>' + highlight(code, EmacsLispLexer(), HtmlFormatter()) + '</pre></div>') if code[0:4] == 'bash': text.replace('<div class="highlight"><pre>' + highlight(code, BashLexer(), HtmlFormatter()) + '</pre></div>') if code[0:7] == 'hexdump': text.replace('<div class="highlight"><pre>' + highlight(code, HexdumpLexer(), HtmlFormatter()) + '</pre></div>') if code[0:6] == 'django': text.replace('<div class="highlight"><pre>' + highlight(code, DjangoLexer(), HtmlFormatter()) + '</pre></div>') return (text)
def consolidation_page(): form = Form1() pygmented_text = '' the_css = '' if request.method == 'POST' and form.validate(): ATTR = [ 'style', 'class', 'width', 'height', 'lang', 'align', 'face', 'size', 'cellspacing', 'cellpadding' ] TAGS = ['font', 'span', 'u'] attr = [ "c_{}".format(x) in request.form \ for x in ATTR] tags = [ "c_{}".format(x) in request.form \ for x in TAGS] htmlcode = clean_html(request.form['text'], attr=[x[1] for x in zip(attr, ATTR) if x[0]], tags=[x[1] for x in zip(tags, TAGS) if x[0]]) form.text.data = htmlcode pygmented_text = highlight(htmlcode, HtmlLexer(), HtmlFormatter(style='colorful')) the_css = HtmlFormatter(style='colorful').get_style_defs() return render_template('myform.html', form=form, pygmented_text=pygmented_text, the_css=the_css) else: return render_template('myform.html', form=form, pygmented_text=pygmented_text, the_css=the_css)
def pygmentize(html): return highlight(html, HtmlLexer(), html_formatter)
def listitems(request): url_type = request.POST.get("type", "") #python power url_tag = request.session['url'] import requests from bs4 import BeautifulSoup as bs soup = bs(requests.get(url_tag).text, "html.parser") if url_type == "Images": imagelinks = soup.find_all("img") imgw = [] template = "imglist.html" for link in imagelinks: hr = link.get("src") imgurl = requests.compat.urljoin(url_tag, hr) imgw = imgw + [imgurl] if len(imgw) == 0: return render( request, template, { "notfound": "No image Found", "url": "Downloading from : " + url_tag, "namee": url_tag, }, ) else: return render( request, template, { "imgw": imgw, "url": "Downloading from : " + url_tag, "namee": url_tag, }, ) elif url_type == "Videos": videolinks = soup.find_all("source") vidw = [] template = "vidlist.html" for link in videolinks: hr = link.get("src") vodurl = requests.compat.urljoin(url_tag, hr) vidw = vidw + [vodurl] if len(vidw) == 0: return render( request, template, { "notfound": "No Videos found", "url": "Downloading from : " + url_tag, "namee": url_tag, }, ) else: return render( request, template, { "vidw": vidw, "url": "Downloading from : " + url_tag, "namee": url_tag, }, ) elif url_type == "Scripts": csslinks = soup.find_all("script") cssw = [] cssone = [] for link in csslinks: hr = link.get("src") cssurl = requests.compat.urljoin(url_tag, hr) cssw = cssw + [cssurl] cssone = cssone + [requests.get(cssurl).text] if len(cssw) == 0: return render( request, "csslist.html", { "url": "Downloading from " + url_tag, "namee": url_tag, "notfound": "No scripts found" }, ) else: return render( request, "csslist.html", { "url": "Downloading from " + url_tag, "namee": url_tag, "cssw": cssw, "cssone": cssone, }, ) elif url_type == "Audios": audiolinks = soup.find_all('source') audw = [] for link in audiolinks: hr = link.get('src') audurl = requests.compat.urljoin(url_tag, hr) audw = audw + [audurl] if len(audw) == 0: return render( request, "audiolist.html", { "url": "Downloading from " + url_tag, "namee": url_tag, "notfound": "No Audio Found", }, ) else: return render( request, "audiolist.html", { "url": "Downloading from " + url_tag, "namee": url_tag, "audw": audw, }, ) elif url_type == "CSS": csslinks = soup.find_all("link") cssw = [] cssone = [] for link in csslinks: hr = link.get("href") cssurl = requests.compat.urljoin(url_tag, hr) cssw = cssw + [cssurl] cssone = cssone + [requests.get(cssurl).text] if len(cssw) == 0: return render( request, "csslist.html", { "url": "Downloading from " + url_tag, "namee": url_tag, "notfound": "No Css Scripts Found" }, ) else: return render( request, "csslist.html", { "url": "Downloading from " + url_tag, "namee": url_tag, "cssw": cssw, "cssone": cssone, }, ) elif url_type == "Source": from pygments import highlight from pygments.formatters import HtmlFormatter from pygments.lexers import HtmlLexer #html lexer he = highlight(soup.prettify(), HtmlLexer(), HtmlFormatter()) return render( request, "linklist.html", { "source": format_html(he), "url": "Source of : " + url_tag, }, ) elif url_type == "Tags": return render(request, "linklist.html", {"url": "Coming soon"}) elif url_type == "Help": return render( request, "help.html", {}, ) elif url_type == "About": return render( request, "about.html", {}, ) else: ty = "404"
def render_page(self, root, file): input_file = os.path.join(root, file) output_file = self.__get_page_filename(input_file) partial = yaml.load(open(input_file, "r").read()) url_root = os.getenv("ROOT_DIRECTORY") or "" # if main index page, add version number from VERSION.txt if self.__is_main_index(output_file): partial['content'] = pystache.render( partial['content'], {"version": self.get_version()}) else: partial['pageHeading'] = partial['pageTitle'] partial['pageTitle'] = (partial['pageTitle'] + " - Digital Marketplace frontend toolkit") if "examples" in partial: template_name, template_extension = os.path.splitext(file) template_subfolder = root.replace(self.pages_dirname, "").strip("/") env = Environment(loader=FileSystemLoader( os.path.join(self.repo_root, "toolkit/templates"))) env.filters.update({ 'markdown': markdown_filter, }) # used in `toolkit/templates/summary-table.html` for a conditional import statement env.globals['PAGES_BUILDER'] = True template_file = os.path.join(template_subfolder, template_name + ".html") template = env.get_template(template_file) examples = [] for index, example in enumerate(partial["examples"]): if isinstance(example, dict): example_template = self.parameters_example( template_subfolder, template_name, example) example_markup = template.render(example) else: example_template = example example_markup = env.from_string( example_template).render({}) examples.append({ "parameters": highlight(example_template, DjangoLexer(), HtmlFormatter(noclasses=True)), "markup": example_markup, "highlighted_markup": highlight(example_markup, HtmlLexer(), HtmlFormatter(noclasses=True)) }) partial_data = { "examples": examples, "pageTitle": partial['pageTitle'], "pageDescription": partial.get('pageDescription'), "pageHeading": partial['pageHeading'], "templateFile": template_file, "urlRoot": url_root } if "grid" in partial: partial_data['grid'] = partial['grid'] partial['content'] = self.render_include( os.path.join(self.repo_root, "pages_builder", "includes", "content.html"), partial_data) partial['head'] = self.render_include( os.path.join(self.repo_root, "pages_builder", "includes", "head.html"), {"url_root": url_root}) bodyEnd = partial['bodyEnd'] if "bodyEnd" in partial else "" partial['bodyEnd'] = self.render_include( os.path.join(self.repo_root, "pages_builder", "includes", "bodyEnd.html"), { "url_root": url_root, "bodyEnd": bodyEnd }) page_render = pystache.render(self.template_view, partial) print "\n " + input_file print "▸ " + output_file open(output_file, "w+").write(page_render.encode('utf-8'))
options_menu.add_cascade(label=lang['options'][4], menu=music_menu) options_menu.add_separator() options_menu.add_command(label=lang['options'][5], command=textbox.scrap_page) options_menu.add_command(label=lang['options'][6], command=textbox.highlight_all) style_menu.add_command(label=lang['style'][0], command=lambda: textbox.tagger('bold')) style_menu.add_command(label=lang['style'][1], command=lambda: textbox.tagger('italic')) style_menu.add_command(label=lang['style'][2], command=lambda: textbox.tagger('underline')) syntax_menu.add_command(label='Python 3', command=lambda: textbox.set_lexer(Python3Lexer())) syntax_menu.add_command(label='C/C++', command=lambda: textbox.set_lexer(CppLexer())) syntax_menu.add_command(label='C#', command=lambda: textbox.set_lexer(CSharpLexer())) syntax_menu.add_command(label='Java', command=lambda: textbox.set_lexer(JavaLexer())) syntax_menu.add_command(label='Rust', command=lambda: textbox.set_lexer(RustLexer())) syntax_menu.add_command(label='Go', command=lambda: textbox.set_lexer(GoLexer())) syntax_menu.add_command(label='HTML', command=lambda: textbox.set_lexer(HtmlLexer())) syntax_menu.add_command(label='CSS', command=lambda: textbox.set_lexer(CssLexer())) syntax_menu.add_command(label='Javascript', command=lambda: textbox.set_lexer(JavascriptLexer())) syntax_menu.add_command(label='PHP', command=lambda: textbox.set_lexer(PhpLexer())) syntax_menu.add_command(label='SQL', command=lambda: textbox.set_lexer(SqlLexer())) syntax_menu.add_command(label='Batch', command=lambda: textbox.set_lexer(BatchLexer())) syntax_menu.add_command(label='Bash', command=lambda: textbox.set_lexer(BashLexer())) syntax_menu.add_command(label='Markdown', command=lambda: textbox.set_lexer(MarkdownLexer())) for font_name in settings["fonts"]: font_menu.add_command(label=font_name, command=lambda font_name=font_name: textbox.change_font(font_name, 0)) for size in range(settings["min_font_size"], settings["max_font_size"] + settings["font_size_interval"], settings["font_size_interval"]): font_size_menu.add_command(label=size, command=lambda size=size: textbox.change_font(size, 1))
elif message['level'] == 'error': color = 'red' prefix = "[ ERROR ]" elif message['level'] == 'debug': color = 'green' prefix = "[ DEBUG ]" elif message['level'] == 'info': color = 'blue' prefix = "[ INFO ]" text = colored(" ".join([prefix, message['text']]), color) locked_print(text) js_lexer = JavascriptLexer() html_lexer = HtmlLexer() formatter = TerminalFormatter() def pretty_print(class_name=None, value=None): class_name = colored("[ {} ]".format(class_name), 'yellow') if class_name else "" if type(value) == dict: value = json.dumps(value) lexer = html_lexer if "HTML" in class_name else js_lexer value = highlight(str(value), lexer, formatter)[:-1] output = filter(lambda out: out != None, [class_name, value]) locked_print(" ".join(output)) def run():
def render_page(self, root, file): input_file = os.path.join(root, file) output_file = self.__get_page_filename(input_file) partial = yaml.safe_load(open(input_file, "r").read()) url_root = os.getenv("ROOT_DIRECTORY") or "" print("\n " + input_file) # for index pages, we want to render variables in the content # - add version number from package.json to the main index page # - add urlRoot to the nested 'index.html' pages if 'index.html' in output_file: partial['content'] = pystache.render( partial['content'], {"version": self.get_version()}) else: partial['pageHeading'] = partial['pageTitle'] partial['pageTitle'] = (partial['pageTitle'] + " - Digital Marketplace frontend toolkit") examples_html_only = 'examples_html_only' in partial if "examples" in partial: template_name, template_extension = os.path.splitext(file) template_subfolder = root.replace(self.pages_dirname, "").strip("/") env = ToolkitEnvironment(loader=FileSystemLoader( os.path.join(self.repo_root, "toolkit/templates"))) env.add_extension('jinja2.ext.with_') template_file = os.path.join(template_subfolder, template_name + ".html") template = None # not all of our examples have template files (`_lists.scss`, for example) if os.path.isfile( os.path.join(self.repo_root, "toolkit/templates", template_file)): template = env.get_template(template_file) has_template = True else: has_template = False examples = [] for index, example in enumerate(partial["examples"]): grid = partial.get('grid') # If a pattern doesn't have a template in the toolkit, use the jinja from the example if not has_template: template = env.from_string(example) if isinstance(example, dict): # if the example has some html it needs to be displayed, # cache it and remove from the parameters example surrounding_html = example.get('surrounding_html', None) if surrounding_html: del example['surrounding_html'] example_template = self.parameters_example( template_subfolder, template_name, example) example_markup = template.render(example) if surrounding_html: example_markup = env.from_string( surrounding_html).render( {'example': example_markup}) # set a grid if specified. Example-level grids will overwrite the one for the page grid = example.get('grid', partial.get('grid')) else: example_template = example example_markup = env.from_string( example_template).render({}) examples.append({ "markup": example_markup, "highlighted_markup": highlight(example_markup, HtmlLexer(), HtmlFormatter(noclasses=True)), "grid": grid }) if template and not examples_html_only: examples[-1].update({ "parameters": highlight(example_template, DjangoLexer(), HtmlFormatter(noclasses=True)) }) partial_data = { "examples": examples, "pageTitle": partial['pageTitle'], "pageDescription": partial.get('pageDescription'), "pageHeading": partial['pageHeading'], "templateFile": template_file, "urlRoot": url_root } if "grid" in partial: partial_data['grid'] = partial['grid'] partial['content'] = self.render_include( os.path.join(self.repo_root, "pages_builder", "includes", "content.html"), partial_data) partial['head'] = self.render_include( os.path.join(self.repo_root, "pages_builder", "includes", "head.html"), {"url_root": url_root}) bodyEnd = partial['bodyEnd'] if "bodyEnd" in partial else "" partial['bodyEnd'] = self.render_include( os.path.join(self.repo_root, "pages_builder", "includes", "bodyEnd.html"), { "url_root": url_root, "bodyEnd": bodyEnd }) page_render = pystache.render(self.template_view, partial) print("▸ " + output_file) open(output_file, "wb+").write(page_render.encode('utf-8'))
#!/usr/bin/env python import argparse from pygments.lexers import HtmlLexer # ============================================================================= parser = argparse.ArgumentParser( description=('Prints out the tokens ' 'generated by pygments.lexers.HtmlLexer')) parser.add_argument('files', type=str, nargs='+', help='One or more file names to lex and parse') args = parser.parse_args() # --- Do the parsing lexer = HtmlLexer() with open(args.files[0]) as f: contents = f.read() for token, text in lexer.get_tokens(contents): first = ord(text[0]) if text == '\n': text = '\\n' print('%s: %s %0x' % (token, text, first))
def Lexer_Html(self, Thread, Code): out = highlight(Code, HtmlLexer(), TerminalFormatter()) Thread.kill = True return out