Back to site
Since 2004, our University project has become the Internet's most widespread web hosting directory. Here we like to talk a lot about web servers, web development, networking and security services. It is, after all, our expertise. To make things better we've launched this science section with the free access to educational resources and important scientific material translated to different languages.

Plope



Kontrolna Verzija Skladišta
_______________________________________________________________________________________________________________________
http://svn.supervisord.org/meld3

Takođe vidite
_______________________________________________________________________________________________________________________
Zope 3 meld3 bindings (z3meld)

Pregled
_______________________________________________________________________________________________________________________
Meld3 je HTML/XML sistem templiranja za Python 2.3+ koji drži oznake i dinamičku rendering lokigu odvojenu jednu od druge. Idite na http://www.entrian.com/PyMeld da vidite raspravu o korisnosti ovog obrasca...

Meld3 može da se nosi sa HTML ili XML/XHTML inputima i može poslati dobro formiran HTML ili XML/XHTML.

Meld3 je varijacija Paul Winkler-ove Meld2 verzije, koja je u stvari varijacija modela PyMeld od strane Ricchie Hindles-a.

Meld3 koristi Element Tree biblioteku konstruisanu od Frederik Lundh-a.

Uslovi
_______________________________________________________________________________________________________________________
Python 2.3 +

1.2 + Element skup (http://effbot.org/downloads/#elementtree)

Instalacija
_______________________________________________________________________________________________________________________
Pokrenite python setup.py install.

Razlika između PyMeld-a
_______________________________________________________________________________________________________________________
  • Šabloni kreirani za upotrebu ispod PyMeld verzije neće raditi u meld3 verziji usled razlika u meld tag identifikaciji (meld3.id atributi se nalaze u nestandardnom XML prostoru imena, dok kod PyMeld nisu). Obrazloženje: trebalo bi biti moguće pogledati šablon i imati na umu koji delovi bi mogli da budu zamenjeni sa dinamičkim sadržajem. XML identifikacije su obavezne zbog drugih stvari kao CSS stilovi, tako da ne možete da pretpostavite da li vidite XML id u šablonu koji je ovde stavljen da bude meld identifikator. U najgorem mogućem slučaju, ako su XML ids bili korišćeni umesto ids imena prostora, i nekorišćeni id je prikazan u izvornom dokumentu, dizajner bi ostavio to ovde čak i ako ga nije koristio zbog toga što misli da je bilo korišćeno od strane dizajneskih list stilova. U međuvremenu, ga niko u stvari i ne koristi i to samo zatrpava šablon. Takođe, imanjem odvojenih imena prostora pomaže programeru da ne stompuje na dizajneru menjanjem identifikatora (ili kod potrebe za hvatanjem list stilova), i dozvoljavanjem im da izbegnu svađu oko zvanja elemenata.
  • Atributi “id” koji su korišćeni za označavanje se nalaze u odvojenim imenima prostora (aka xmins= "http://www.plope.com/softvware/meld3”). Tako da u stvari umesto da označite tag kao ovaj : <div id="thediv"></div>, meld3 zahteva da kvalifikujete “id” atribut sa “med” imenom prostora elementom kao ovaj: <div id="thediv"></div>. Prema XML imenu prostora specifikaciji “meld” ime je kompletno opciono, i mora biti prikazano sa “ http://www.plope.com/software/meld3” identifikatorom imena prostora, tako da <div meld:id=”thediv”/>.
  • Izlazna dokumenta po standardu ne obuhvataju bilo kakve meld3 namespace id atribute. Ako želite da sačuvate meld3 ids-ove ( na primer, kako bi uradili povezivanje meld3 šablona), možete sačuvati meld ids prebacivanjem “pipeline” opcije do “write” funkcije ( npr. write_xml, write_xhtml)..
  • Autput može funkcionisati u “XML modu”, “XHTML modu” i “HTML modu”. HTML izlaz sledi preporuke za HTML 4.01, dok XML i XHTML izlaz izbacuje validni XML ako kreirate prazni element prostora teksta i izbacite ga u XML i XHTML modu, izalaz će biti renderovani <textarea/>. U HTML modu će biti renderovan kao <textarea><textarea>. U HTML modu, različiti drugi tagovi kao img nisu “balansirani” sa završnim tagom, i tako dalje. Možete odlučiti kako želite da rednerujete vaše šablone slanjem html zastavice do meld write.
  • meld3 elementi su primeri ElementTree elemenata i podržavaju ЕlementTree_ElementInterface API) umesto PyMeld Api čvora. ElementTree_ElementInterface API je bio proširen od strane meld3 da izvodi različite funkcije specifične za meld3.
  • meld3 elementi ne podržavaju _mod_method sa nizom argumenta, ali podržavaju _mod_method sa rečnik argumentom, ipak.
  • meld3 elementi podržavaju različite ZPT slične metode kao “repeat”, “content”, “attributes”, i “replace” koje su namenjene da rade kao njihove ZTP kolege.


Primeri
_______________________________________________________________________________________________________________________

Validni primer meld3 šablona, kao što sledi:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:meld="http://www.plope.com/software/meld3"
          xmlns:bar="http://foo/bar">
      <head>
        <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type" />
        <title meld:id="title">This is the title</title>
      </head> 
      <body>
        <div/> <!-- empty tag -->
        <div meld:id="content_well">
          <form meld:id="form1" action="." method="POST">
          <table border="0" meld:id="table1">
            <tbody meld:id="tbody">
              <tr>
                <th>Name</th>
                <th>Description</th>
              </tr>
              <tr meld:id="tr" class="foo">
                <td meld:id="td1">Name</td>
                <td meld:id="td2">Description</td>
              </tr>
            </tbody>
          </table>
          <input type="submit" name="next" value=" Next "/>
          </form>
        </div>
      </body>
    </html>


Imajte da umu da skripta ne sadrži logiku, samo “meld:id” identifikatore. Svi “meld:id” identifikatori u jednom dokumentu moraju biti jednistveni za meld šablon da bi bili u mogućnosti za parsovanje.

Skripta koja parira šablon iznad i obavlja neke transformacije se nalazi ispod. Smatrajte da je promenjivi “xml” ispod ograničen za niz, predstavlja XHTML koji se nalazi iznad:

    from meld3 import parse_xmlstring
    from meld3 import parse_htmlstring
    from StringIO import StringIO
    import sys

    root = parse_xmlstring(xml)
    root.findmeld('title').content('My document')
    root.findmeld('form1').attributes(action='./handler')
    data = (
        {'name':'Boys',
         'description':'Ugly'},
        {'name':'Girls',
         'description':'Pretty'},
        )
    iterator = root.findmeld('tr').repeat(data)
    for element, item in iterator:
        element.findmeld('td1').content(item['name'])
        element.findmeld('td2').content(item['description'])


Koristili ste “parse_xmlstring” funkciju da bi transformisali XML do šeme čvorova koja se nalazi iznad. Ovo je bilo moguće zato što je input bio dobro formirani XML. Da nije dobro formiran,umesto toga trebali bi da koristite “parse_htmlstring” funkciju.

Da bi izbacili rezultat transformacije do stdout kao XML, koristimo write metod bilo kog elementa. Ispod, koristimo korenski element (smatrajte ga kao granicom do vrednosti “korena” u skripti iznad):

    import sys
    root.write_xml(sys.stdout)
    ...
    <?xml version="1.0"?>
    <html:html xmlns:html="http://www.w3.org/1999/xhtml">
      <html:head>
        <html:meta content="text/html; charset=ISO-8859-1" http-equiv="content-type" />
        <html:title>My document</html:title>
      </html:head>
      <html:body>
        <html:div /> <!--  empty tag  -->
        <html:div>
          <html:form action="./handler" method="POST">
          <html:table border="0">
            <html:tbody>
              <html:tr>
                <html:th>Name</html:th>
                <html:th>Description</html:th>
              </html:tr>
              <html:tr class="foo">
                <html:td>Boys</html:td>
                <html:td>Ugly</html:td>
              </html:tr>
            <html:tr class="foo">
                <html:td>Girls</html:td>
                <html:td>Pretty</html:td>
              </html:tr>
            </html:tbody>
          </html:table>
          <html:input name="next" type="submit" value=" Next " />
          </html:form>
        </html:div>
      </html:body>
    </html:html>


Takođe možemo serijalizovati našu šemu elemenata kao dobro formirani XHTML, koji je u velikoj meri isti kao renderovanje do XML-a, osim što po standardu ne emituje XML deklaraciju i sklanja sva “html” imena prostora iz autputa. Takođe emituje XHTML loose dokument tip deklaraciju, blizu vrha dokumenta:

    import sys
    root.write_xhtml(sys.stdout)
    ...
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
      <head>
        <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type" />
        <title>My document</title>
      </head>
      <body>
        <div /> <!--  empty tag  -->
        <div>
          <form action="./handler" method="POST">
          <table border="0">
            <tbody>
              <tr>
                <th>Name</th>
                <th>Description</th>
              </tr>
              <tr class="foo">
                <td>Boys</td>
                <td>Ugly</td>
              </tr>
            <tr class="foo">
                <td>Girls</td>
                <td>Pretty</td>
              </tr>
            </tbody>
          </table>
          <input name="next" type="submit" value=" Next " />
          </form>
        </div>
      </body>
    </html>


Mi takođe možemo izbaciti tekst u HTML modu. Ovo serijalizuje čvor (node) i njegove čvoriće do HTML-a (ova karakteristika je inspirisana i bazirana na kodu Ian Bicking-a). Standardno, serijalizacija će uključiti loose HTML DTD dokoument tip (ovo može da se prebriše sa doctype=argument). Ali neki HTML tagovi (definisani prema HTML 4 spec kao: area,base, fontbase, br,col, ram, hr, img, input, is index, meta, param) neće slediti sa balansiranim završnim tagom; samo će početni tag biti autput. Dodatno, “boolean” tag atributi neće biti praćeni sa bilo kakvom vrednošću. “Boolean” tagovi su selected, checked, compact, declare, delay, multiple, defer, noresize, nohref. Tako da će XML input <input type=”checkbox” checked=”checked”/> biti promenjeu u <input type=”checkbox” checked>. Dodatno, script i style tagovi neće ostati bez svog sadržaja (npr. tako “&” neće biti promenjen u & kad se nalazi unutar tekstualnog sadžaja skripte ili tag stila.):

    import sys
    root.write_html(sys.stdout)
    ...
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
      <head>
        <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
        <title>My document</title>
      </head>
      <body>
        <div></div> <!--  empty tag  -->
        <div>
          <form action="./handler" method="POST">
          <table border="0">
            <tbody>
              <tr>
                <th>Name</th>
                <th>Description</th>
              </tr>
              <tr class="foo">
                <td>Boys</td>
                <td>Ugly</td>
              </tr>
            <tr class="foo">
                <td>Girls</td>
                <td>Pretty</td>
              </tr>
            </tbody>
          </table>
          <input name="next" type="submit" value=" Next ">
          </form>
        </div>
      </body>
    </html>


API Element
_______________________________________________________________________________________________________________________ Elementi meld3 podržavaju sve ElementTree_ElementInterface API. Slede ostali meld specifični metodi:

    "clone(parent=None)": clones a node and all of its children via a
    recursive copy.  If parent is passed in, append the clone to the
    parent node.

    "findmeld(name, default=None)": searches the this element and its
    children for elements that have a 'meld:id' attribute that matches
    "name"; if no element can be found, return the default.

    "meldid()": Returns the "meld id" of the element or None if the element
    has no meld id.

    "repeat(iterable, childname=None)": repeats an element with values
    from an iterable.  If 'childname' is not None, repeat the element on
    which repeat was called, otherwise find the child element with a
    'meld:id' matching 'childname' and repeat that.  The element is
    repeated within its parent element.  This method returns an
    iterable; the value of each iteration is a two-sequence in the form
    (newelement, data).  'newelement' is a clone of the template element
    (including clones of its children) which has already been seated in
    its parent element in the template. 'data' is a value from the
    passed in iterable.  Changing 'newelement' (typically based on
    values from 'data') mutates the element "in place".

    "replace(text, structure=False)": (ala ZPT's 'replace' comnand)
    Replace this element in our parent with a 'Replace' node
    representing the text 'text'.  Return the index of the index
    position in our parent that was replaced.  If 'structure' is true,
    at rendering time, the outputted text will not be escaped in the
    serialization.  If we have no parent, do nothing, and return None.
    This method leaves a special kind of node in the element tree (a
    'Replace' node) to represent the replacement.  NOTE: This command
    has the potential to cause a non-well-formed XML/HTML
    serialization at render time if "structure" is True.

    "content(text, structure=False)": (ala ZPT's 'content' command)
    Delete every child element in this element and append a Replace
    node that contains 'text'.  Always return None.  If 'structure' is
    true, at rendering time, the outputted text will not be escaped in
    the serialization.  If we have no parent, do nothing, and return
    None.  NOTE: This command has the potential to cause a
    non-well-formed XML/HTML serialization at render time if
    "structure" is True.

    "attributes(**kw)": (ala ZPT's 'attributes' command) For each key
    value pair in the kw list, add an attribute to this node where the
    attribute's name is 'key' and the attributes value is 'value'.
    Keys and values must be string or unicode types, else a ValueError
    is raised.  Returns None.

    "__mod__(other)": Fill in the text values of meld nodes in this
    element and children recursively; only support dictionarylike
    "other" operand (sequence operand doesn't seem to make sense here).

    "fillmelds(**kw)":Fill in the text values of meld nodes in this
    element and children recursively.  Return the names of keys in the
    **kw dictionary that could not be found anywhere in the tree.  Never
    raise an exception.

    "write_xml(file, encoding=None, doctype=None, fragment=False, 
    declaration=True, pipeline=False)":
    Write XML to 'file' (which can be a filename or filelike object)
    encoding    -- encoding string (if None, 'utf-8' encoding is assumed)
                   Must be a recognizable Python encoding type.
    doctype     -- 3-tuple indicating name, pubid, system of doctype.
                   The default is to prevent a doctype from being emitted.
    fragment    -- True if a 'fragment' should be emitted for this node (no
                   declaration, no doctype).  This causes both the
                   'declaration' and 'doctype' parameters to become ignored
                   if provided.
    declaration -- emit an xml declaration header (including an encoding
                   if it's not None).  The default is to emit the
                   doctype.
    pipeline    -- preserve 'meld' namespace identifiers in output
                   for use in pipelining

    "write_xhtml(self, file, encoding=None, doctype=doctype.xhtml,
    fragment=False, declaration=False, pipeline=False)":
    Write XHTML to 'file' (which can be a filename or filelike object)

    encoding    -- encoding string (if None, 'utf-8' encoding is assumed)
                   Must be a recognizable Python encoding type.
    doctype     -- 3-tuple indicating name, pubid, system of doctype.
                   The default is the value of doctype.xhtml (XHTML
                   'loose').
    fragment    -- True if a 'fragment' should be emitted for this node (no
                   declaration, no doctype).  This causes both the
                   'declaration' and 'doctype' parameters to be ignored.
    declaration -- emit an xml declaration header (including an encoding
                   string if 'encoding' is not None)
    pipeline    -- preserve 'meld' namespace identifiers in output
                   for use in pipelining

    Note that despite the fact that you can tell meld which doctype to
    serve, meld does no semantic or syntactical validation of
    attributes or elements when serving content in XHTML mode; you as
    a programmer are still responsible for ensuring that your
    rendering does not include font tags, for instance.

    Rationale for defaults: By default, 'write_xhtml' doesn't emit an
    XML declaration because versions of IE before 7 apparently go into
    "quirks" layout mode when they see an XML declaration, instead of
    sniffing the DOCTYPE like they do when the xml declaration is not
    present to determine the layout mode.  (see
    http://hsivonen.iki.fi/doctype/ and
    http://blogs.msdn.com/ie/archive/2005/09/15/467901.aspx).
    'write_xhtml' emits a 'loose' XHTML doctype by default instead of
    a 'strict' XHTML doctype because 'tidy' emits a 'loose' doctye by
    default when you convert an HTML document into XHTML via
    '-asxhtml', and I couldn't think of a good reason to contradict
    that precedent.

    A note about emitting the proper Content-Type header when serving
    pages rendered with write_xhtml: you can sometimes use the
    content-type 'application/xhtml+xml' (see
    "http://www.w3.org/TR/xhtml-media-types/#application-xhtml-xml").
    The official specification calls for this.  But not all browsers
    support this content type (notably, no version of IE supports it,
    nor apparently does Safari).  So these pages *may* be served using
    the 'text/html' content type and most browsers will attempt to do
    doctype sniffing to figure out if the document is actually XHTML.
    It appears that you can use the Accepts header in the request to
    figure out if the user agent accepts 'application/xhtml+xml' if
    you're a stickler for correctness.  In practice, this seems like
    the right thing to do.  See
    "http://keystonewebsites.com/articles/mime_type.php" for more
    information on serving up the correct content type header.

    "write_html(self, file, encoding=None, doctype=doctype.html,fragment=False)":
    Write HTML to 'file' (which can be a filename or filelike object)
    encoding    -- encoding string (if None, 'utf-8' encoding is assumed).
                   Unlike XML output, this is not used in a declaration,
                   but it is used to do actual character encoding during
                   output.  Must be a recognizable Python encoding type.
    doctype     -- 3-tuple indicating name, pubid, system of doctype.
                   The default is the value of doctype.html (HTML 4.0
                   'loose')
    fragment    -- True if a "fragment" should be omitted (no doctype).
                   This overrides any provided "doctype" parameter if
                   provided.
    Namespace'd elements and attributes have their namespaces removed
    during output when writing HTML, so pipelining cannot be performed.
    HTML is not valid XML, so an XML declaration header is never emitted.

    In general: For all output methods, comments are preserved in
    output.  They are also present in the ElementTree node tree (as
    Comment elements), so beware. Processing instructions (e.g. '<?xml
    version="1.0">') are completely thrown away at parse time and do
    not exist anywhere in the element tree or in the output (use the
    declaration= parameter to emit a declaration processing
    instruction).


API Parsiranje
_______________________________________________________________________________________________________________________

Izvorni tekst XML je promenjen u šemi elemenata pomoću “parse_xmlstring” funkcije (demonstrirana u primeru iznad). Funkcija koja prihvata objekat imena fajla ili objekat fajl like umesto niza, ali koja izvodi istu funkciju koja se zove “parse_xml”.

    from meld3 import parse_xml
    from meld3 import parse_xmlstring


Izvorni tekst HTML je promenjen u šemi elemenata pomoću “parse_htmlstring” funkcije. Fukcija koja prihvata ime fajla i fajl like objekte umesto niza, ali izvodi istu funkciju koja se zove “parse_html”.

    from meld3 import parse_html
    from meld3 import parse_htmlstring


Korišćenje dupliranih meld identifikatora u izvornom dokumentu uzrokuje grešku vrednosti da se pokrene u vreme parsiranja.

Kada se koristi parse_xml i parse_xmlstring, dokument koji sadrži reference entiteta (npr. <nbsp;) treba imati entitete definisane u izvornom dokumentu ili moraju imati DOCTYPE deklaraciju koja dozvoljava te entitete da budu rešeni od strane expat parsera.

Kada se koristi parse_xml i parse_xmlstring, input dokument mora uključiti meld3 ime prostora deklaraciju (konvencionalno na korenu elementa). Na primer: <html xmlns:мeld="http://www.plope.com/sowtware/meld3>...</html>

parse_html i parse_htmlstring uzimaju argument opciono kodiranje koji specifikuje kodiranje izvornog dokumenta.
Da se uradi
_______________________________________________________________________________________________________________________
Još uvek API nije finaliziran.

Ova implementacija zavisi od unutrašnjih klasa šeme elemenata i nije bila testirana sa cElementTree ili Ixml, i skoro sigurno neće raditi sa nijednim zbog ovoga.

Pogledajte TODO.txt za više informacija “kako da se uradi” stavki.

Izveštavanje o greškama i Zahtevajuće karakteristike
_______________________________________________________________________________________________________________________
Molimo vas da posetite http://www.plope.com/software/collector da prijavite greške i šaljete zahteve za karakteristike.




Published (Last edited): 23-02-2013 , source: http://plope.com/software/meld3