HTML avançado

Neste artigo, gostaria de contar um pouco sobre a biblioteca, cuja primeira versão eu criei no final do ano passado. O ponto é muito simples - expandir os recursos da linguagem HTML para que você possa escrever coisas simples e rotineiras sem JavaScript: enviando o formulário no formato json, carregando arquivos de modelo HTML em uma página específica (essencialmente um sistema modular para HTML via solicitações http / s), turbinas ( oi para usuários do RoR), um modelo simples baseado nas respostas de solicitações de ajax e um pouco mais.


imagem


A biblioteca é chamada EHTML ou HTML estendido. É baseado na idéia notória de componentes da web . Está disponível no github , há documentação bastante bem estruturada com exemplos. Neste artigo, descreverei simplesmente as idéias principais, talvez elas sejam direcionadas a alguém.


Conexão de biblioteca


Para começar, para usá-lo, você não precisa das ferramentas npm ou cli para criar um projeto; tudo o que é necessário é a página HTML em que você inclui o script da biblioteca:


<head>
  <script src="/../js/ehtml.bundle.min.js" type="text/javascript"></script>
</head>

Sistema modular


Vamos começar com uma simples - compilando uma página HTML de muitas outras:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <script src="/../js/ehtml.bundle.min.js" type="text/javascript"></script>
  </head>

  <body class="main">
    <div class="articles">
      <e-html data-src="/../html/first.html"></e-html>
      <e-html data-src="/../html/second.html"></e-html>
      <e-html data-src="/../html/third.html"></e-html>
    </div>
  </body>
</html>

Para fazer isso, usamos um elemento personalizado e-htmlque possui um único atributo data-src, onde indicamos onde a parte HTML da página é distribuída. Ou seja, se, por exemplo, first.htmlfor algo parecido com isto:


<div class="article">
  <!-- some content of the first article -->
</div>

finalmente, nossa página será renderizada da seguinte maneira:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <script src="/../js/ehtml.bundle.min.js" type="text/javascript"></script>
  </head>

  <body class="main">
    <div class="articles">
      <div class="article">
        <!-- content of the first article -->
      </div>
      <div class="article">
        <!-- content of the second article -->
      </div>
      <div class="article">
        <!-- content of the third article -->
      </div>
    </div>
  </body>
</html>

Ou seja, as tags e-htmlserão substituídas pelo conteúdo do arquivo HTML que especificamos no data-srcatributo


<template/>. . e-wrapper, . <template/> is="e-wrapper" - . :


<!-- /../html/wrapper.html -->
<div class="base">
  <p>
    Header content
  </p>
  <p id="dynamic-content">
    <span>Default content</span>
  </p>
  <p>
    Footer content
  </p>
</div> 

, :


<body class="main">
  <template 
    is="e-wrapper" 
    data-src="/../html/wrapper.html" 
    data-where-to-place="#dynamic-content" 
    data-how-to-place="instead">
    <p>
      Variation of content
    </p>
  </template>
</body>

, :


<div class="base">
  <p>
    Header content
  </p>
  <p>
    Variation of content
  </p>
  <p>
    Footer content
  </p>
</div> 

data-src HTML , . data-where-to-place , e-wrapper . data-how-to-place . : instead( , data-where-to-place), before( ) after ( ). , e-html e-wrapper html . http , , — .


ajax


, json :


/../album/{title}
title = 'Humbug'
{
  "title": "Humbug",
  "artist": "Arctic Monkeys",
  "type": "studio album",
  "releaseDate": "19 August 2009",
  "genre": "psychedelic rock, hard rock, stoner rock, desert rock",
  "length": "39:20",
  "label": "Domino",
  "producer": "James Ford, Joshua Homme"
}

is="e-json", HTML:


<template is="e-json" data-src="/../album/Humbug" data-object-name="albumResponse">
  <div data-text="Title: ${albumResponse.body.title}"></div>
  <div data-text="Artist: ${albumResponse.body.artist}"></div>
  <div data-text="Type: ${albumResponse.body.type}"></div>
  <div data-text="Release date: ${albumResponse.body.releaseDate}"></div>
  <div data-text="Genre: ${albumResponse.body.genre}"></div>
  <div data-text="Length: ${albumResponse.body.length}"></div>
  <div data-text="Label: ${albumResponse.body.label}"></div>
  <div data-text="Producer: ${albumResponse.body.producer}"></div>
</template>

data-src , json , data-object-name — , http : body, headers statusCode. data-text , e-json .


. , :


title = 'Humbug'
{
  "title": "Humbug",
  "artist": "Arctic Monkeys",
  "songs": [
    { "title": "My Propeller", "length": "3:27" },
    { "title": "Crying Lightning", "length": "3:43" },
    { "title": "Dangerous Animals", "length": "3:30" },
    { "title": "Secret Door", "length": "3:43" },
    { "title": "Potion Approaching", "length": "3:32" },
    { "title": "Fire and the Thud", "length": "3:57" },
    { "title": "Cornerstone", "length": "3:18" },
    { "title": "Dance Little Liar", "length": "4:43" },
    { "title": "Pretty Visitors", "length": "3:40" },
    { "title": "The Jeweller's Hands", "length": "5:42" }
  ]
}

e-for-each :


<template is="e-json" data-src="/../album/Humbug" data-object-name="albumResponse">
    <div data-text="Title: ${albumResponse.body.title}"></div>
    <div data-text="Artist: ${albumResponse.body.artist}"></div>

    <div><b data-text="${albumResponse.body.songs.length} songs:"></b></div>
    <template 
      is="e-for-each"
      data-list-to-iterate="${albumResponse.body.songs}"
      data-item-name="song">
      <div class="song-box">
        <div data-text="No. ${song.index}/${album.songs.length}"></div>
        <div data-text="Title: ${song.title}"></div>
        <div data-text="Length: ${song.length}"></div>
      </div>
    </template>
</template>

data-list-to-iterate , . data-item-name , e-for-each .


e-for-each e-if :


<template is="e-json" data-src="/../album/Humbug" data-object-name="albumResponse">
    <div data-text="Title: ${albumResponse.body.title}"></div>
    <div data-text="Artist: ${albumResponse.body.artist}"></div>

    <div><b data-text="${albumResponse.body.songs.length} songs:"></b></div>
    <template is="e-for-each" 
      data-list-to-iterate="${albumResponse.body.songs}" 
      data-item-name="song">
      <template 
         is="e-if"
         data-condition-to-display="${(song.length.split(':')[0] * 60 + song.length.split(':')[1] * 1) <= 210}"
      >
        <div class="song-box">
          <div data-text="No. ${song.index}/${album.songs.length}"></div>
          <div data-text="Title: ${song.title}"></div>
          <div data-text="Length: ${song.length}"></div>
        </div>
      </template>
    </template>
</template>

data-condition-to-display e-if , .



— . json , e-form, .


, / :


/artist/{name}/albums/add 
name = 'Arctic Monkeys'
POST
Example of expected request body: {
  "title": "Humbug",
  "type": "studio album",
  "releaseDate": "19 August 2009",
  "genre": ["psychedelic rock", "hard rock", "stoner rock", "desert rock"],
  "length": "39:20",
  "label": "Domino",
  "producer": "James Ford, Joshua Homme"
}

, :


<e-form>

  Title:
  <input type="text" name="title">

  Type:
  <input type="radio" name="type" value="studio album" checked>
  <label for="one">One</label>

  <input type="radio" name="type" value="live album" checked>
  <label for="one">One</label>

  Release date:
  <input type="date" name="releaseDate">

  Genre:
  <input type="checkbox" name="genre" value="psychedelic rock">
  <input type="checkbox" name="genre" value="hard rock">
  <input type="checkbox" name="genre" value="stoner rock">
  <input type="checkbox" name="genre" value="desert rock">

  Total length:
  <input type="time" name="totalLength">

  Producer:
  <input type="text" name="producer">

  <button
    id="send"
    data-request-url="/artist/Arctic_Monkeys/albums/add"
    data-request-method="POST"
    data-request-headers="{}"
    data-ajax-icon="#ajax-icon"
    data-response-name="savedAlbum"
    onclick="this.form.submit(this)"
    data-actions-on-response="
      logToConsole('response: ', '${savedAlbum}');
    "
  />

  <img id="ajax-icon" src="/../images/ajax-loader.gif"/>

</e-form>

, , , . , , . ajax , . , — . , . .



Se você estiver interessado na idéia e quiser experimentar a biblioteca em ação ou apenas aprender algo mais, a biblioteca README possui informações abrangentes sobre os elementos suportados. Você também pode assistir a um vídeo em que escrevo um aplicativo de blog simples exclusivamente usando EHTML.


Ficarei feliz em responder a perguntas, se surgirem. E obrigado pela atenção!


Link para nabos .


All Articles