yawrap Documentation Release Michal Kaczmarczyk

Similar documents
yawrap Documentation Release Michal Kaczmarczyk

Introduction to WEB PROGRAMMING

CSS.

Welcome Please sit on alternating rows. powered by lucid & no.dots.nl/student

Session 4. Style Sheets (CSS) Reading & References. A reference containing tables of CSS properties

Cascading Style Sheets Level 2

Make a Website. A complex guide to building a website through continuing the fundamentals of HTML & CSS. Created by Michael Parekh 1

In the early days of the Web, designers just had the original 91 HTML tags to work with.

Stamp Builder. Documentation. v1.0.0

.hedgehog { background-image: url(backyard.jpg); color: #ffff99; height: 6in; width: 12in; } .tube {

The Benefits of CSS. Less work: Change look of the whole site with one edit

CSS: The Basics CISC 282 September 20, 2014

HTML Summary. All of the following are containers. Structure. Italics Bold. Line Break. Horizontal Rule. Non-break (hard) space.

Html basics Course Outline

Introduction to Multimedia. MMP100 Spring 2016 thiserichagan.com/mmp100

As we design and build out our HTML pages, there are some basics that we may follow for each page, site, and application.

Styles, Style Sheets, the Box Model and Liquid Layout

Introduction to Computer Science Web Development

Table Basics. The structure of an table

HTML & CSS November 19, 2014

Assignments (4) Assessment as per Schedule (2)

How to lay out a web page with CSS

Introduction to Web Design CSS Reference

Introduction to Web Design CSS Reference

Block & Inline Elements

CSS. Lecture 16 COMPSCI 111/111G SS 2018

Unveiling the Basics of CSS and how it relates to the DataFlex Web Framework

CSCB20 Week 7. Introduction to Database and Web Application Programming. Anna Bretscher Winter 2017

To link to an external stylesheet, the link element is placed within the head of the html page:

Cascading Style Sheet. Styles as Tag Attributes. Syntax. <h1>: what font type/size is used? STYLE = SELECTOR {RULES} Attributes such as bgcolor

INTRODUCTION TO CSS. Mohammad Jawad Kadhim

CSS Lecture 16 COMPSCI 111/111G SS 2018

Chapter 1 Getting Started with HTML 5 1. Chapter 2 Introduction to New Elements in HTML 5 21

Creating your first website Part 4: Formatting your page with CSS

Cascading Style Sheets (CSS)

Deccansoft Software Services

LING 408/508: Computational Techniques for Linguists. Lecture 14

Lab Introduction to Cascading Style Sheets

CSS: Cascading Style Sheets

Unit 10 - Client Side Customisation of Web Pages. Week 5 Lesson 1 CSS - Selectors

Appendix D CSS Properties and Values

Controlling Appearance the Old Way

INTRODUCTION TO CSS. Topics MODULE 5

Data Visualization (CIS/DSC 468)

Study Guide 2 - HTML and CSS - Chap. 6,8,10,11,12 Name - Alexia Bernardo

<style type="text/css"> <!-- body {font-family: Verdana, Arial, sans-serif} ***set font family for entire Web page***

Index. alt, 38, 57 class, 86, 88, 101, 107 href, 24, 51, 57 id, 86 88, 98 overview, 37. src, 37, 57. backend, WordPress, 146, 148

Chapter 3 Style Sheets: CSS

Final Exam Study Guide

Introduction to HTML & CSS. Instructor: Beck Johnson Week 2

Lecture : 3. Practical : 2. Course Credit. Tutorial : 0. Total : 5. Course Learning Outcomes

NAVIGATION INSTRUCTIONS

HTML & CSS. SWE 432, Fall 2017 Design and Implementation of Software for the Web

<body bgcolor=" " fgcolor=" " link=" " vlink=" " alink=" "> These body attributes have now been deprecated, and should not be used in XHTML.

CSS مفاهیم ساختار و اصول استفاده و به کارگیری

CS 350 COMPUTER/HUMAN INTERACTION. Lecture 6

CSS: formatting webpages

Zen Garden. CSS Zen Garden

Web Development & Design Foundations with HTML5, 8 th Edition Instructor Materials Chapter 3 Test Bank

3.1 Introduction. 3.2 Levels of Style Sheets. - The CSS1 specification was developed in There are three levels of style sheets

- The CSS1 specification was developed in CSS2 was released in CSS2.1 reflects browser implementations

2. Write style rules for how you d like certain elements to look.

Indian Institute of Technology Kharagpur. HTML Part III. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T.

READSPEAKER ENTERPRISE HIGHLIGHTING 2.5

CSS worksheet. JMC 105 Drake University

Web and Apps 1) HTML - CSS

ICT IGCSE Practical Revision Presentation Web Authoring

Adding CSS to your HTML

8/19/2018. Web Development & Design Foundations with HTML5. Learning Objectives (1 of 2) Learning Objectives (2 of 2)

Using Dreamweaver CS6

CSS Cascading Style Sheets

How to create and edit a CSS rule

ICT IGCSE Practical Revision Presentation Web Authoring

Reading 2.2 Cascading Style Sheets

Creating and Building Websites

Introduction to using HTML to design webpages

Layout with Layers and CSS

Data Visualization (DSC 530/CIS )

HTML and CSS COURSE SYLLABUS

CSS 1: Introduction. Chapter 3

IBM Forms V8.0 Custom Themes IBM Corporation

Website Design (Weekend) By Alabian Solutions Ltd , 2016

Programmazione Web a.a. 2017/2018 HTML5

Getting Started with Eric Meyer's CSS Sculptor 1.0

Static Webpage Development

ADDING CSS TO YOUR HTML DOCUMENT. A FEW CSS VALUES (colour, size and the box model)

CSS Module in 2 Parts

Activity 4.1: Creating a new Cascading Style Sheet

Web Publishing Intermediate 2

Before you begin, make sure you have the images for these exercises saved in the location where you intend to create the Nuklear Family Website.

Web Engineering CSS. By Assistant Prof Malik M Ali

WEB DEVELOPMENT & DESIGN FOUNDATIONS WITH HTML5

Web Designer s Reference

Creating and Building Websites

How to Control and Override CSS by Including a CSS Link

CS 350 Internet Applications I Name: Exam II (CSS) October 29, 2013

Building Your Website

Web Recruitment Module Customisation

Intermediate Web Publishing: Working with Styles

COPYRIGHTED MATERIAL. Contents. Chapter 1: Creating Structured Documents 1

Transcription:

yawrap Documentation Release 0.3.0 Michal Kaczmarczyk Feb 27, 2018

Contents 1 yattag s heritage 3 2 Yawrap features 5 3 Usage Examples 7 4 Contents 15 5 Indices and tables 23 i

ii

Yawrap is a powerful, lightweight pseudo-static HTML builder working in python2.7, python3.4 and python. 3.5. The name comes from something like Yet Another Wrapper (of HTML tags) and has its coincidence to yattag package. resource Repo: Docs: Pypi: email: link https://bitbucket.org/gandowin/yarap http://yawrap.readthedocs.io https://pypi.python.org/pypi/yawrap Michał Kaczmarczyk Contents 1

2 Contents

CHAPTER 1 yattag s heritage Yawrap s core is yattag. It s a ultra-lightweight library written by Benjamin Le Forestier. Yattags s main functionality is care of proper opening and closing HTML (actually XML) tags. However if you use yattag you probably noticed that in order to create a nice HTML page, you have to write a lot of code that is not exactly the content of your page and each time you have to care for the same aspects of the page - such as proper html head/body structure, links, navigation ect... Yawrap extends yattag s functionality (and adds some more). Note: Yawrap classes are derived from Yattag s Doc() class. So you can use e.g. its tag, line, text, methods in the same way. Yattag is well documented and its strongly recommend to read its awesome quick reference. 3

4 Chapter 1. yattag s heritage

CHAPTER 2 Yawrap features Here is a list of things that yawrap offers: CSS & JS support Append internal CSS styles or JS at any point of document definition. Allows for conditional additions of CSS or JS.... and you don t have to care about when to insert its definition. Even if you already finished defining the body and you define JS after that - it will be placed in /html/head/. You can also easily link style sheet or java script from external file (local or from web). SVG support Don t care about defining SVG structure, just write its main contents. Yawrap will take care about the whole rest. Also typical SVG attributes which are problematic from python keyword-arguments point of view have it s convenience feature. Linking local files You can reference local files by passing its absolute path on python side and it will appear under links relative to the current document. And you don t have to calculate the paths. Defining page style and scripts on python class level Page styles can be defined by deriving Yawrap classes. This makes possibility to get the styles shared / inherited / override in well known pythonic way. Multi-page structure Define multiple pages in complex directory structure and don t care about the paths. Not existing directories will be automatically created, you just define the path of target file. Automatic navigation That s ultra-nice. Probably the cutest yawrap s feature. Create multiple pages and see how yawrap joins them in navigation panel created for each generated page. Everything happens behind the curtains. The only one thing you need to do is to care for the navigation s CSS style (if you don t like the default navigation style provided by Yawrap). Bookmarking Create intra-page bookmarks with just one command during document definition and see how they are inserted in correct subsection of the page navigation. 5

6 Chapter 2. Yawrap features

CHAPTER 3 Usage Examples Because a good example is worth more than thousand words. 3.1 Basic Usage This is a tiny basic example. Such a code is sufficient to generate an html page. Passing target file location to Yawrap constructor is mandatory, although the file will be not generated until Yawrap. render() is called. Title is optional. from yawrap import Yawrap def hello_yawrap(out_file_path): jawrap = Yawrap(out_file_path, "The title") with jawrap.tag('h2'): jawrap.text('hello yawrap!') with jawrap.tag('p'): jawrap.text('could it be simpler?') jawrap.render() file_path) # add a header # add a paragraph # and its content # that creates html file (under out_ Will create such an page: Which looks like this: 7

3.2 Basic JS usage More realistic usage. It s an adaptation of following example: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_fadetoggle from yawrap import Yawrap, ExternalJs, EmbedCss, EmbedJs, BODY_END class MyPageTemplate(Yawrap): resources = [ ExternalJs("https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js "), EmbedCss(""" body { padding: 12px; font-family: helvetica, sans-serif; font-size: 14px; }.box { display: inline-block; height: 80px; margin: 8px; padding: 8px; width: 80px; } """), EmbedJs(""" $("button").click(function(){ $("#red-box").fadetoggle(); $("#green-box").fadetoggle("slow"); $("#blue-box").fadetoggle(3000); }); """, placement=body_end), ] def _create_box(self, name, color): style = "background-color:{};".format(color) with self.tag('div', id=name, klass="box", style=style): self.text(name) def fill_with_content(self): with self.tag("h2"): self.text("demonstrate a simple JavaScript.") with self.tag('p'): self.text("fadetoggle() operating with different speed parameters.") with self.tag('button'): self.text("click to fade in/out boxes") with self.tag("div"): self._create_box('red-box', "red") self._create_box('green-box', "#0f0") self._create_box('blue-box', "#0a1cf0") 8 Chapter 3. Usage Examples

def create_page(output_file_path): doc = MyPageTemplate(output_file_path, "Name of the page") doc.fill_with_content() doc.render() # that's it Will create a page as below. Note that the placement=body_end in EmbedJs call caused the script to be placed at the end. Withouth that argument it would get into head section. That looks like this: 3.3 Usage 2 A example of table build on complex JSON-like structure, also presenting information about CSS & JS supplementation in Yawrap. from yawrap import NavedYawrap, EmbedCss from collections import namedtuple Deploy = namedtuple("deploy", "as_internal_content, as_local_link, as_web_url") RS = namedtuple("rs", "css, js") Info = namedtuple("info", "code, note") class ResourceInfoPage(NavedYawrap): resources = [ EmbedCss(""" body { padding: 12px; font-family: Arial, Helvetica, sans-serif; } table, th, td { border: 1px solid #b0baba; border-collapse: collapse; } tr, td { padding: 10px 8px; } ul { margin: 2px; padding: 2px 2px 2px 14px; } th { padding: 16px 8px; }.header { padding: 15px; font-weight: bold; }.code { padding: 4px; font-family: "Lucida Console", Monaco, monospace; font- size: 85%; color: #060; }""") ] def build_the_table(doc, header, data): with doc.tag("table"): for elem_idx, type_name in enumerate(rs._fields): with doc.tag("tr"): with doc.tag("td", klass="header", colspan=4): doc.text(type_name) with doc.tag("tr"): with doc.tag("th"): doc.text('source') for column in header: with doc.tag("th"): doc.text(column[elem_idx]) 3.3. Usage 2 9

for row in data: with doc.tag("tr"): with doc.tag("td"): doc.text(str(row["source"])) for column in row["deploy"]: code = column[elem_idx] with doc.tag("td"): if code is not None: with doc.tag("ul"): for code_line in code.code: with doc.tag("li", klass="code"): doc.text(code_line) with doc.tag("div"): doc.text(code.note) else: doc.text("not applicable") HEADER = Deploy( as_internal_content=rs( css="embed / Insert style sheet into html page.", js="embed / Insert java script into html page." ), as_local_link=rs( css="reference style sheet file as local resource", js="reference java script file as local resource" ), as_web_url=rs( css="reference style sheet file by it's url", js="reference java script file by it's url" ), ) GUIDE = [ { "source": "from string", "deploy": Deploy( as_internal_content=rs( css=info(["embedcss(the_style_as_string)"], ""), js=info(["embedjs(the_script_as_string)"], "") ), as_local_link=rs( css=info([ "LinkCss(the_style_as_string, file_name = 'file_name.css')", ], "Providing the file name is required."), js=info([ "LinkJs(the_script_as_string, file_name='file_name.js')", "LinkJs(the_script_as_string, file_name='file_name.js', placement=yawrap.body_begin)", "LinkJs(the_script_as_string, file_name='file_name.js', placement=yawrap.body_end)", ], "Providing the file name is required. By default the link will appear in head. " "You can select different placement if needed.") ), as_web_url=rs( css=none, js=none 10 Chapter 3. Usage Examples

) ) }, { "source": "from local file", "deploy": Deploy( as_internal_content=rs( css=info(["embedcss.from_file('/path/to/the_source.css')"], "The file must exist"), js=info([ "EmbedJs.from_file('/path/to/the_source.js')", "EmbedJs.from_file('/path/to/the_source.js', placement=yawrap. BODY_END)"], "The source file must exist. You can change placement (HEAD is default)"), ), as_local_link=rs( css=info([ "LinkCss.from_file('/path/to/the_source.css')", "LinkCss.from_file('/path/to/the_source.css', file_name= 'different_name.css')", ], "By default - target file name is same as the source's name. Name can be changed."), js=info([ "LinkJs.from_file('/path/to/the_source.js')", "LinkJs.from_file('/path/to/the_source.js', file_name='different_ name.js')", "LinkJs.from_file('/path/to/the_source.js', file_name='different_ name.js', placement=yawrap.body_begin)", "LinkJs.from_file('/path/to/the_source.js', file_name='different_ name.js', placement=yawrap.body_end)", ], "The source file must exist. You can change the name or the link placement (HEAD is default)") ), as_web_url=rs( css=none, js=none ) ) }, { "source": "from the web", "deploy": Deploy( as_internal_content=rs( css=info(["embedcss.from_url('https://url.to/the.style.css')"], ""), js=info(["embedjs.from_url('https://url.to/the.script.js')"], "") ), as_local_link=rs( css=info([ "LinkCss.from_url('https://url.to/the.style.css')", "LinkCss.from_url('https://url.to/the.style.css', file_name= 'different_name.css')", ], ""), js=info([ "LinkJs.from_url('https://url.to/the.script.js')", "LinkJs.from_url('https://url.to/the.script.js', file_name= 'different_name.css.js')", "LinkJs.from_url('https://url.to/the.script.js', file_name= 'different_name.css.js', placement=yawrap.body_end)", 3.3. Usage 2 11

] }, ) ], "") ), as_web_url=rs( css=info(["externalcss('https://url.to/the.style.css')"], ""), js=info(["externaljs('https://url.to/the.script.js')"], "") ) 3.4 Ways to feed it with CSS / JS resources There are several possibilities to place a CSS and JS in html page. Each has some advantages. Yawrap helps handling probably all of them. from yawrap import Yawrap class PlainPage(Yawrap): resources = [] doc = PlainPage("/tmp/test.html") doc.render() Will create a page that has no style sheet (and no content) defined. It s just to show the Tabula rasa case, when the resources list is empty. OK, but of course you would like to use the styles and scripts. 3.4.1 External resources This is how to reference resources hosted on external server. from yawrap import ExternalCss, ExternalJs class PageWithExternalCss(Yawrap): resources = [ ExternalCss.from_url("https://www.w3schools.com/w3css/4/w3.css"), ExternalJs.from_url("https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/ jquery.min.js"), ] That gives: Disadvantage of such approach is of course - dependency on other web resource,... but Yawrap doesn t care it s your business. 12 Chapter 3. Usage Examples

3.4.2 Auto-Linked resources Yawrap can download the sheet or script given by URL (while page build), save it as a local file and manage its relative path calculation. Just replace ExternalCss with LinkCss and ExternalJs with LinkJs like this: from yawrap import LinkCss, LinkJs class LinkedCssPage(Yawrap): resources = [ LinkCss.from_url("https://www.w3schools.com/w3css/4/w3.css"), LinkJs.from_url("https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery. min.js"), ] With such a result: See how these link point to local files in resources directory? It s a default location, next to output html file. Yawrap created it while build. Let s say it once again Yawrap downloads and saves the files with each run. If you allways want to get a fresh copy from these urls, it s ok. But it s probably eaiser to download it manually, save it close to your yawrap generator code. While each run, yawrap will source its contents from local files, instead of the web. Rest (i.e. saving to target resources dir) is the same as before. Such a code will source the linked code from given files: class LocalSources(Yawrap): resources = [ LinkCss.from_file("path/to/source_of/w3.css"), LinkJs.from_file("path/to/source_of/jquery.min.js"), ] 3.4.3 Changing default resources path The default resources output directory can be changed like this: class LinkCssInMyStyle(LinkCss): resource_subdir = "the_super_directory" # for nested structure, do: # # resource_subdir = os.path.join("the", "super", "directory") class LinkJsInMyStyle(LinkJs): resource_subdir = "" # empty string will same dir, as parent html class MyStyleOfLinking(Yawrap): 3.4. Ways to feed it with CSS / JS resources 13

resources = [ LinkCssInMyStyle.from_url("https://www.w3schools.com/w3css/4/w3.css"), LinkJsInMyStyle.from_url("https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/ jquery.min.js"), ] This code will generate exactly the same HTML, just paths differ. Note that JS and CSS will go to separate dirs. Note: Relative path management makes sense when several pages from different paths share same CSS/JS file. E.g. when NavedYawrap is in use. Then the resources directory path is threated as relative to the top level of output directory structure (relative to root, the first page). 3.4.4 Defining CSS / JS in python code Sometimes you would like to keep definition of the CSS or JS inside a python module. Especially if you use python for generating it (e.g. calculate CSS colors, margin sizes, etc..) Then there are If you are interested with getting single-file page (all-in-one, no linked CSS nor JS), where everything is embedded in single html, then use such an pattern: Replacing a resource sourcer LinkCss with EmbedCss as here: LinkCss.from_url("https://www.w3schools.com/w3css/4/w3.css") EmbedCss.from_url("https://www.w3schools.com/w3css/4/w3.css") # with will cause downloading the w3 style sheet and placing it directly to the /html/head/style section. The download happens with each call of Yawrap.render(). It also embeds additional style for body defined as a python string. The most useful in my opinion is to create own class derived from Yawrap (or NavedYawrap or whatever from the family). 14 Chapter 3. Usage Examples

CHAPTER 4 Contents 4.1 CSS Support Yawrap has it s basic support of cascade style sheets. During creation of html page you can append styles definition as strings or dictionaries. It will appear in /html/head/style section of current yawrap document. Also linking CSS as external file is possible. Note: The class keyword, widely used in html/css will cause python s syntax error if used as keyword argument, so you can define it by typing klass instead. Yattag will convert it to class automatically. 4.1.1 Internal CSS as str from yawrap import Yawrap, EmbedCss out_file = '/tmp/css_1.html' jawrap = Yawrap(out_file) with jawrap.tag('div', klass='content'): with jawrap.tag('span'): jawrap.text('css in yawrap.') jawrap.add(embedcss('''.content { margin: 2px; }.content:hover { background-color: #DAF; }''')) jawrap.render() print(open(out_file, 'rt').read()) That outputs: 15

<!doctype html> <html lang="en-us"> <head> <meta charset="utf-8" /> <style>.content { margin: 2px; }.content:hover { background-color: #DAF; }</style> </head> <body> <div class="content"> <span>css in yawrap.</span> </div> </body> </html> The method add() called with action EmbedCss() appends CSS definitions to page head section. It can be called several times, output CSS will be sorted and nicely joined. The passed CSS can be a string without any formatting. It will be reformatted during page generation. 4.1.2 Internal CSS as python s dict The argument passed to add_css() can be a regular python dictionary definins css. css_dict = { '.content': { 'color': '#321', 'padding': '1px 16px' }, 'span': { 'border': '1px solid black' } } # reusing jawrap instance from subsection above. jawrap.add(embedcss(css_dict)) jawrap.render() print(open(out_file, 'rt').read()) Will give: <!doctype html> <html lang="en-us"> <head> <meta charset="utf-8" /> <style>.content { margin: 2px; }.content:hover { background-color: #DAF; }</style> <style>.content { color: #321; padding: 1px 16px; } 16 Chapter 4. Contents

span { border: 1px solid black; }</style> </head> <body> <div class="content"> <span>css in yawrap.</span> </div> </body> </html> Note the previous.content selector s definition is overwritten with new one. 4.1.3 External CSS from local file It s also possible to link style sheet from local file. It s source can be placed anywhere as long as it s accessible for build process. Yawrap will copy it and place in default resources directory, next to target file (or next to root document): from yawrap import Yawrap, LinkCss out_file = '/tmp/css_2.html' jawrap = Yawrap(out_file) jawrap.text('css from local file.') jawrap.add(linkcss.from_file('/tmp/files/my.css')) jawrap.render() 4.1.4 External CSS from web Using global CSS from some resources can be obtained by calling add() with ExternalCss object. from yawrap import Yawrap, ExternalCss out_file = '/tmp/css_3.html' jawrap = Yawrap(out_file) jawrap.text('css from web.') jawrap.add(externalcss("https://www.w3schools.com/w3css/4/w3.css")) jawrap.render() file_content = open(out_file, 'rt').read() expected_result = """\ <!doctype html> <html lang="en-us"> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css" type="text/ css" /> </head> <body>css from web.</body> </html>""" from bs4 import BeautifulSoup print(beautifulsoup(file_content, "lxml") == BeautifulSoup(expected_result, "lxml")) 4.1. CSS Support 17

True 4.1.5 CSS defined on class level You can derive own class from Yawrap or Navrap class and define its CSS that will be inherited in its subclasses. You have to define css class attribute either as a string or a dictionary. from yawrap import Yawrap, EmbedCss out_file = '/tmp/css_4.html' class MyStyledPage(Yawrap): resources = [EmbedCss(''' body { margin: 0px; padding: 13px 14px; }.content { color: #BAC; margin: 2px; }''') ] mystyled = MyStyledPage(out_file) with mystyled.tag('div', klass='content'): mystyled.text('deriving CSS.') mystyled.render() print(open(out_file, 'rt').read()) Should give: <!doctype html> <html lang="en-us"> <head> <meta charset="utf-8" /> <style> body { margin: 0px; padding: 13px 14px; }.content { color: #BAC; margin: 2px; }</style> </head> <body> <div class="content">deriving CSS.</div> </body> </html> Adding CSS is still possible, but to instance of the derived class (to mystyled above), not to the class definition (here MyStyledPage), so the appended CSS will not be inherited. 18 Chapter 4. Contents

4.2 JavaScript support Yattag does not modify nor even analyze added js sources. You provide them as strings and these are rendered in /html/head/script section. Each addition places the content in separate <script> section. Of course there is also possibility to link external js source file. 4.2.1 Internal JS Appending js to Yawrap or Navrap instances can be done appending string-code to Class Note: Yawrap has a class-level atribute being a list named js. It is supposed to contain JavaScript code as strings. Similary as with CSS, you can derive from Yawrap class and also define the class-level JS that will be inherited by its subclasses unless you override it. 4.2.2 Using jquery It s an adaptation of following example: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_fadetoggle from yawrap import Yawrap, ExternalJs, EmbedCss, EmbedJs, BODY_END class MyPageTemplate(Yawrap): resources = [ ExternalJs("https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js "), EmbedCss(""" body { padding: 12px; font-family: helvetica, sans-serif; font-size: 14px; }.box { display: inline-block; height: 80px; margin: 8px; padding: 8px; width: 80px; } """), EmbedJs(""" $("button").click(function(){ $("#red-box").fadetoggle(); $("#green-box").fadetoggle("slow"); $("#blue-box").fadetoggle(3000); }); """, placement=body_end), ] def _create_box(self, name, color): style = "background-color:{};".format(color) with self.tag('div', id=name, klass="box", style=style): 4.2. JavaScript support 19

self.text(name) def fill_with_content(self): with self.tag("h2"): self.text("demonstrate a simple JavaScript.") with self.tag('p'): self.text("fadetoggle() operating with different speed parameters.") with self.tag('button'): self.text("click to fade in/out boxes") with self.tag("div"): self._create_box('red-box', "red") self._create_box('green-box', "#0f0") self._create_box('blue-box', "#0a1cf0") def create_page(output_file_path): doc = MyPageTemplate(output_file_path, "Name of the page") doc.fill_with_content() doc.render() # that's it Will create a page as below. Note that the placement=body_end in EmbedJs call caused the script to be placed at the end. Withouth that argument it would get into head section. That looks like this: 4.2.3 Sharing scripts and styles across multiple pages Similar effect as above but with reusable java scripts and CSS can be obtained by defining them as class level attributes like this: from yawrap import LinkCss, LinkJs class MyPage(MyPageTemplate): resources = [ ExternalJs("https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js "), LinkCss(""" body { padding: 12px; font-family: helvetica, sans-serif; font-size: 14px; }.box { display: inline-block; height: 80px; margin: 8px; padding: 8px; width: 80px; 20 Chapter 4. Contents

] }""", file_name="common_linked.css"), LinkJs(""" $("button").click(function(){ $("#red-box").fadetoggle(); $("#green-box").fadetoggle("slow"); $("#blue-box").fadetoggle(3000); }); """, placement=body_end, file_name="common_linked.js"), # uses methods inherited from MyPageTemplate defined above def create_page_with_linked_resources(output_file_path): doc = MyPage(output_file_path) doc.fill_with_content() doc.render() Which produces the page:..and the script resources/common_linked.js:..and the style resources/common_linked.css: 4.3 Multiple-page structure with navigation It s easy to navigate between several files in different paths, using sub() method of NavedYawrap instance. Each call of sub() returns instance of given NavedYawrap class, with same styles and scripts as the parent one. Each page will be rendered with navigation section, with relative paths. See the hrefs in the example below. The first document (home in this example) will be the root of the document structure. def test_naved_yawrap(): from exampling_tools import get_output_file_path from yawrap import NavedYawrap, EmbedCss class MyPage(NavedYawrap): resources = [EmbedCss(""" body { margin: 16; font-family: Verdana, sans-serif; }""") ] out_file_1 = get_output_file_path("nav01a.html") home = MyPage(out_file_1, title="title Force One") # fill content of root document with home.tag('p'): home.text("i'm home") # create a sub-document out_file_2 = get_output_file_path(os.path.join("some", "deep", "nonexistent", "path", "nav01b.html")) 4.3. Multiple-page structure with navigation 21

about = home.sub(out_file_2, 'Abouting') with about.tag('div'): about.text('always do the abouting!') home.render_all_files() # at this point files are generated Generates two html pages: Notice, how the href is calculated. Here s the page: 4.4 Examples This is a tiny example. Such a code is sufficient to generate an html page: >>> from yawrap import Yawrap >>> jawrap = Yawrap('/tmp/example_1.html', 'the title') >>> with jawrap.tag('div'):... with jawrap.tag('p'):... jawrap.text('nothing much here.') After executing that - calling render() function will store the page in a target file specified in Yawrap constructor: >>> jawrap.render() >>> print(open('/tmp/example_1.html', 'rt').read()) <!doctype html> <html lang="en-us"> <head> <meta charset="utf-8" /> <title>the title</title> </head> <body> <div> <p>nothing much here.</p> </div> </body> </html> Note: That 22 Chapter 4. Contents

CHAPTER 5 Indices and tables genindex modindex search 23