Home >Backend Development >Golang >How to Dynamically Update Template Partials in Go?

How to Dynamically Update Template Partials in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-24 10:52:15563browse

How to Dynamically Update Template Partials in Go?

Dynamically Update Template Partials in Go

In Go, the ability to refresh a portion of a template when a variable is modified is not inherently supported. To achieve this functionality, a custom solution must be implemented.

Implementation Steps:

  1. Refactor Templates: Extract the section rendering the Addresses into a separate template block using {{define "Addresses"}} or {{block "Addresses"}}.
  2. Modify/Create Handlers: Create a handler that exclusively executes the Addresses template and sends the output to the HTTP response. This handler can be used independently or within the handler for the full page template.
  3. Client-Side Logic: On the client side, perform an AJAX call to the Addresses handler when you need to update the displayed addresses. Replace the content of the Addresses wrapper element with the response from the AJAX call.

Steps in Detail:

  1. Template Refactoring:

    {{define "Addresses"}}
      <ul>
      {{range $key, $value := .Addresses}}
     <li>{{ $key }}: {{ $value }}</li>
      {{end}}
      </ul>
    {{end}}
  2. Handler Modification:

    import "net/http"
    
    func AddressesHandler(w http.ResponseWriter, r *http.Request) {
      data := map[string]string{"Addresses": []string{"Address1", "Address2"}}
      t, err := template.New("AddressesTemplate").Parse("{{define "Addresses"}}{{.Addresses}}{{end}}")
      if err != nil {
     http.Error(w, http.StatusInternalServerError.String(), http.StatusInternalServerError)
     return
      }
      err = t.ExecuteTemplate(w, "Addresses", data)
      if err != nil {
     http.Error(w, http.StatusInternalServerError.String(), http.StatusInternalServerError)
     return
      }
    }
  3. Client-Side Implementation:

    var addressesElement = document.getElementById("addresses");
    
    function refreshAddresses() {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", "/addresses", true);
      xhr.onreadystatechange = function() {
     if (xhr.readyState === 4 && xhr.status === 200) {
       addressesElement.outerHTML = xhr.responseText;
     }
      };
      xhr.send();
    }

Alternative Framework:

Gowut is a Go web framework that provides similar functionality for dynamic partial updates in web pages.

The above is the detailed content of How to Dynamically Update Template Partials in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn