Let's talk about HTML

written in front

I recently read a few articles about htmx, took a look at the official website, and went to Youtube to watch their demo at the htmx press conference. Here are some of my views on this so-called new technology.

what is his source

First of all, let me say that although it is a new type of technology, it is actually a bit of a fried rice. It is actually a rewrite of jQuery's [intercoolerjs](https://intercoolerjs.org/reference.html, that is to say In the past, intercoolerjs has been able to achieve the effect similar to htmx, that is, it does not need to bind any events, directly requests an address from the label, and directly renders the returned information to the corresponding page. These functions already exist. There are also many articles about intercoolerjs on the Internet. If you are interested, you can check it out yourself and quote an official DEMO

<!--
  This is the initial UI (which would normally be generated by the userDisplayTemplate below of course)
  Note that the button targets the outer div which encloses the entire contact UI because that's what we
  want to replace when the button is clicked.
  -->
  <div id="contact-div">
    <div><strong>First Name</strong>: Joe</div>
    <div><strong>Last Name</strong>: Smith</div>
    <div><strong>Email</strong>: joesmith@example.com</div>
    <button ic-target="#contact-div" ic-get-from="/contact/1/edit" class="btn btn-default">
      Click To Edit
    </button>
  </div>

  <script>

    //========================================================================
    // Mock Server-Side HTTP End Points
    //========================================================================
    $.mockjax({
     
     
      url: "/contact/1/edit",
      response: function (settings) {
     
     
        var mockUser = dataStore.findUser("1");
        this.responseText = userFormTemplate(mockUser);
      }
    });

    $.mockjax({
     
     
      url: "/contact/1",
      response: function (settings) {
     
     
        var mockUser = dataStore.findUser("1");
        var params = parseParams(settings.data);
        if (params['_method']== 'PUT') {
     
     
          mockUser.firstName = params['firstName'];
          mockUser.lastName = params['lastName'];
          mockUser.email = params['email'];
        }
        this.responseText = userDisplayTemplate(mockUser);
      }
    });

    //========================================================================
    // Mock Server-Side Templates
    //========================================================================
    function userFormTemplate(mockUser) {
     
     
      // Pretty simple bootstrap form, but note that the form uses an ic-put-to and the cancel button uses
      // an ic-get-from rather than the usual HTML attributes
      return '\
<form ic-put-to="/contact/1" ic-target="#contact-div"> \
  <div class="form-group"> \
    <label>First Name</label> \
    <input type="text" class="form-control" name="firstName" value="' + mockUser.firstName + '"> \
  </div> \
  <div class="form-group"> \
    <label>Last Name</label> \
    <input type="text" class="form-control" name="lastName" value="' + mockUser.lastName + '"> \
  </div> \
  <div class="form-group"> \
    <label>Email address</label> \
    <input type="email" class="form-control" name="email" value="' + mockUser.email + '"> \
  </div> \
  <button class="btn btn-default">Submit</button> \
  <button ic-get-from="/contact/1" ic-target="#contact-div" class="btn btn-danger">Cancel</button> \
</form>';
    }

    function userDisplayTemplate(mockUser) {
     
     
      return '\
<div><strong>First Name</strong>: ' + mockUser.firstName + '</div> \
<div><strong>Last Name</strong>: ' + mockUser.lastName + '</div> \
<div><strong>Email</strong>: ' + mockUser.email + '</div> \
<button ic-target="#contact-div" ic-get-from="/contact/1/edit" class="btn btn-default"> \
  Click To Edit \
</button>';
    }

    //========================================================================
    // Mock Data Store
    //========================================================================
    var dataStore = (function() {
     
     
      var mockUser = {
     
     
        "firstName": "Joe",
        "lastName": "Smith",
        "email": "[email protected]"
      };
      return {
     
     
        findUser : function(id) {
     
     
          return mockUser
        }
      }
    })()
  </script>

what can he do

Having said that, there is no formal demonstration of what it can do. What it can do is to directly write some things that js can do on the html tags. His purpose is to de-js, write as little or no writing as possible js code, because we know that the browser actually only understands html code, and it has an inherent advantage in compiling html code, that is to say, if there is only html code in our code, the rendering speed is theoretically very fast, but he It depends on the server, that is, the js code before our front end has not disappeared, but it has been executed on the server side. It can also be seen from the above code, so what it can do is to send what request on what label, request He will specify where to put the returned content, and at the same time, how to design an interaction and feedback with the user in the middle, he will do this, and only do this!

Demo?

  • I also tried its function myself, and it is relatively simple to use. You can directly import CDN or npm i installation in the same way as jQuery, then we can use his syntax directly in html

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>测试 htmx 的用法</title>
    		<script src="./js/[email protected]" integrity="sha384-xcuj3WpfgjlKF+FXhSQFQ0ZNr39ln+hwjN3npfM9VBnUskLolQAcN80McRIVOPuO" crossorigin="anonymous"></script>
    	</head>
    	<body>
    		<script type="text/javascript">
    			// const baseGetRequest = 'http://jsonplaceholder.typicode.com/users'
    			// window.baseGet = baseGetRequest
    		</script>
    		<!-- 测试基础的 get 请求 -->
    		<div hx-get="http://jsonplaceholder.typicode.com/users">
    			Put To Messages
    		</div>
    		<!-- 测试基础的 post 请求  并将请求的结果给到另一个 span 的元素上 -->
    		<div hx-post="http://jsonplaceholder.typicode.com/posts/1/comments" hx-target='#aimDiv'>测试一条数据</div>
    		<span id="aimDiv"></span>
    
    		<!-- 模拟一个对话框的请求 -->
    		<button hx-get="http://jsonplaceholder.typicode.com/users" hx-confirm="Are you sure you wish to delete your account?">
    			Delete My Account
    		</button>
    
    		<!-- 测试一个 boost 的请求 -->
    		<div hx-boost="true">
    			<a href="http://jsonplaceholder.typicode.com/users">Blog</a>
    		</div>
    
    		<!-- 测试一个表单 -->
    		<div id="search-results"></div>
    		<form action="/search" method="POST">
    			<input class="form-control" type="search" name="search" placeholder="Begin typing to search users..." hx-post="http://jsonplaceholder.typicode.com/posts/1/comments" hx-trigger="keyup changed delay:500ms, search" hx-target="#search-results" hx-indicator=".htmx-indicator">
    		</form>
    
    		<!-- 测试 table -->
    		<input class="form-control" type="search" name="search" placeholder="Begin Typing To Search Users..." hx-post="http://jsonplaceholder.typicode.com/posts/1/comments" hx-trigger="keyup changed delay:500ms, search" hx-target="#search-results" hx-indicator=".htmx-indicator">
    		<table class="table">
    			<thead>
    				<tr>
    					<th>First Name</th>
    					<th>Last Name</th>
    					<th>Email</th>
    				</tr>
    			</thead>
    			<tbody id="search-results">
    			</tbody>
    		</table>
    	</body>
    </html>
    

    If you don't understand the labels inside, you can take a look at his official website introduction. Although the htmx official website is in English, the writing is still very clear and generally understandable.

    • The result of executing the above code is as follows:

    insert image description here

Of course, I don’t need to look at the style. I just tried it out and found that when I clicked put to message, the right side sent the request directly. After a while, he directly returned the corresponding content and rendered it for me at the same time, but my The data format is json, so it is unreasonable, you can ignore it, because I just demonstrate that it can return to render normally

insert image description here

what convenience does it provide

  • The request does not require wrapper functions
  • Anti-shake throttling can be configured directly through properties
  • The request method is configured directly through attributes
  • Return reference rendering to an element can be specified
  • There are many ways to specify (css selector, element selector, etc.)
  • The cost of partial content replacement is very low
  • Very little front-end code
  • Browser rendering is fast

what are his disadvantages

  • The size of the project should not be too large, so that the pressure on the server is too great
  • Overly complex operations are not feasible, after all, they are all configured, and configuration means that the degree of satisfaction of customized requirements will not be too high
  • Too much reliance on the server, the front end is just for configuration
  • The dependence on Django is also relatively large, because it is used with him (here I also asked my friend who uses Django around me, and his reply is: jango has built-in web development tools, and you can use {} to directly get the response object Attributes. It was still very powerful in the era when the front and back ends were not separated. It doesn’t work now)

Personal recommendation level, I want to say a few words

It can be used and learned, but because there are not many applicable scenarios, it is enough to understand it, and it can be used when there is a corresponding business! Personally, I still recommend using relatively comprehensive frameworks such as vue and react. He doesn’t pick scenarios. He is competent for almost all web applications. The technology development has finally developed to a stage where the front and back are separated, and now I want to go back. It’s not impossible, it’s not strongly recommended, I won’t repeat the benefits of separating the front and back ends here, and anyone who has developed it for several years can understand it.

Here is a word of complaint. It is a very painful thing to do development in China, because the latest technology is generally passed from abroad. In addition, the first technical documents are all in English, and there are very few Chinese ones, even after translation. Inaccurate, we use inaccurate documents and use languages ​​​​developed by foreigners. It is already a great thing that it can be used very well, but it does not mean that it is right to follow the trend without thinking. For example, this htmx, we clearly know that it is a thing of refractory food, but there are still many people who want to promote it without thinking, only talking about the good, not the bad, as if as long as you keep up with the footsteps of foreign countries, it must be the latest technology. Here I am It is not in favor of it. It is good to explore technology, but it is good to reinvent the wheel. When the wheel comes out and has a name, you can learn according to the new thing. I can’t think of any good reason other than increasing the cost of learning. I hope this situation will be less in the future. Whether it happens or not, I have no malice towards htmx. I think it does solve some application scenarios. They also said at the press conference that if your application needs this kind of scenario, I recommend you to use it, but it is complicated. We do not recommend some of them. You can continue to use the technology stack you think is good, but it will become a great new technology when it is spread to China. I am powerless to complain about it! But learning itself is right, because only if you understand all the different technology stacks, you are more likely to master them. The breadth and depth of technology are very important, and the depth helps to research new technologies. Things, the breadth helps you identify the limitations and applicability of the technology itself, there is too much nonsense, and you are tired of watching it, it is over.

written in the back

After reading this article, you may also feel that this article does not actually have too many code demonstrations, but just talked about its basic usage and applicable scenarios, because I think this thing itself solves some front-end pain points , can not solve the real problem. It actually solves some small and beautiful applications without using relatively heavy frameworks such as vue or react. After all, it still requires a little technical level to configure a set of front-end project shelves, so Here htmx can come in handy, of course, your backend is enough to support you to return the corresponding html code in the early stage

Guess you like

Origin blog.csdn.net/qq_41485414/article/details/132710836