Golang在按钮按下时渲染新模板。

huangapple go评论84阅读模式
英文:

Golang render new template on button press

问题

我有一个按钮,用于将玩家添加到程序中,这是在HTML中完成的。当提交玩家时,我希望该按钮渲染一个新的部分模板。尽管代码已经到达了这一点,但目前并没有发生这种情况。jQuery正常工作并发送正确的数据,只是代码没有渲染新的模板。任何帮助都将是很好的,谢谢。

Go代码:

package main

import (
	"html/template"
	"log"
	"net/http"
	"strings"
)

type playerType struct {
	Fname  string
	Lname  string
	// Men are true and Women are false
	Gender bool
}

var players []playerType

var templates *template.Template

func handleFilePath() {
	http.Handle("/templates/", http.StripPrefix("/templates/", http.FileServer(http.Dir("templates"))))
	http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))

	//templates = template.Must(template.ParseFiles("./templates/index.html", "./templates/displayPlayer.html"))

	templates = template.Must(template.New("").ParseGlob("./templates/*.html"))
}

func landingPage(w http.ResponseWriter, r *http.Request) {
	err := templates.ExecuteTemplate(w, "home", nil)
	if err != nil {
		log.Panicln(err)
		return
	}
}

func addPlayerHandler(w http.ResponseWriter, r *http.Request) {
	Fname := r.FormValue("fname")
	Lname := r.FormValue("lname")
	Gender := r.FormValue("gender")

	if addPlayer(Fname, Lname, Gender) {
		log.Printf("Player added: %v, %v, %v", Fname, Lname, Gender)
		err := templates.ExecuteTemplate(w, "displayPlayer", players[0])
		if err != nil {
			log.Panicln(err)
			return
		}
	}
}

func addPlayer(Fname string, Lname string, Gender string) bool {

	if Fname == "" || Lname == "" || Gender == "" {
		return false
	}

	var playerToBeAdded playerType

	// Set men to true and women to false
	if strings.ToLower(Gender) == "male" {
		playerToBeAdded = playerType{Fname, Lname, true}
	} else {
		playerToBeAdded = playerType{Fname, Lname, false}
	}

	players = append(players, playerToBeAdded)

	return true
}

func main() {
	handleFilePath()
	http.HandleFunc("/", landingPage)

	log.Println("Listening...")

	http.HandleFunc("/addPlayer", addPlayerHandler)

	err := http.ListenAndServe(":8081", nil)
	if err != nil {
		log.Panicln(err)
	}
}

HTML模板:
index.html:

{{ define "home" }}
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/assets/home.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <title>Home - Match Maker</title>
</head>

<body>
<script src="/assets/home.js"></script>

<!-- Button to open the modal login form -->
<button onclick="document.getElementById('id01').style.display='block'" class="addPlayer">Add Player</button>

<button onclick="generateGames()">Generate Games</button>

</br>

{{ template "displayPlayer" .}}

</br>

<!-- The Modal -->
<div id="id01" class="modal">
    <form class="modal-content animate" action="/" method="post">
        <div class="imgcontainer">
            <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">&times;</span>
            <img src="/assets/be.png" alt="Avatar" class="avatar">
        </div>

        <div class="container">
            <label for="fname" style="align-content: center"><b>First Name</b></label>
            <input type="text" placeholder="John" name="firstName" required>

            <label for="lname" style="align-content: center"><b>Last Name</b></label>
            <input type="text" placeholder="Smith" name="lastName" required>
        </div>

        <div class="container">
            Select Gender:
            </br>
            <label>
                <input type="radio" name="gender" value="male" required>Male
            </label>
            </br>
            <label>
                <input type="radio" name="gender" value="female">Female
            </label>
        </div>

        <div class="container" style="background-color:#f1f1f1; text-align: center">
            <button type="button" onclick="document.getElementById('id01').style.display='none'" class="modelButtons">
                Cancel
            </button>
            <button id="subbtn" type="submit" class="modelButtons"
                    onclick="submitPlayer(firstName.value, lastName.value, gender.value)">Submit
            </button>
        </div>
    </form>
</div>
<script>
    // Get the modal
    var modal = document.getElementById('id01');

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function (event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
</script>
</body>
</html>
{{ end }}

displayPlayer.html:

{{ define "displayPlayer" }}
<html lang="en">
<body>
{{ .Fname }}
</br>
{{ .Lname }}
</br>
{{ .Gender }}
</body>
</html>
{{ end }}

Javascript:

home.js:

function submitPlayer(fname, lname, gender) {
    if (fname == "" || lname == "" || gender == "") {
        return;
    }
    $.ajax({
        url: '/addPlayer',
        method: 'post',
        data: {
            fname: fname,
            lname: lname,
            gender: gender,
        },
        success: (d) => {
            console.log("Player Added");
        },
        error: (d) => {
            console.log("An error occurred. Please try again");
        }
    });
}

function generateGames() {
    $.ajax({
        url: '/createGames',
        method: 'post',
        success: (d) => {
            console.log("Generated Games");
        },
        error: (d) => {
            console.log("An error occurred. Please try again");
        }
    });
}
英文:

I have a button which adds a player to the program, this is done in HTML. I would like this button to render a new partial template when the player is submitted. This is currently not happening even though the code is reaching this point. The jQuery is working fine and sending the correct data through, the code is just not rendering the new template. Any help would be great thanks.

Go code:

package main
import (
&quot;html/template&quot;
&quot;log&quot;
&quot;net/http&quot;
&quot;strings&quot;
)
type playerType struct {
Fname string
Lname string
// Men are true and Women are false
Gender bool
}
var players []playerType
var templates *template.Template
func handleFilePath() {
http.Handle(&quot;/templates/&quot;, http.StripPrefix(&quot;/templates/&quot;, http.FileServer(http.Dir(&quot;templates&quot;))))
http.Handle(&quot;/assets/&quot;, http.StripPrefix(&quot;/assets/&quot;, http.FileServer(http.Dir(&quot;assets&quot;))))
//templates = template.Must(template.ParseFiles(&quot;./templates/index.html&quot;, &quot;./templates/displayPlayer.html&quot;))
templates = template.Must(template.New(&quot;&quot;).ParseGlob(&quot;./templates/*.html&quot;))
}
func landingPage(w http.ResponseWriter, r *http.Request) {
err := templates.ExecuteTemplate(w, &quot;home&quot;, nil)
if err != nil {
log.Panicln(err)
return
}
}
func addPlayerHandler(w http.ResponseWriter, r *http.Request) {
Fname := r.FormValue(&quot;fname&quot;)
Lname := r.FormValue(&quot;lname&quot;)
Gender := r.FormValue(&quot;gender&quot;)
if addPlayer(Fname, Lname, Gender) {
log.Printf(&quot;Player added: %v, %v, %v&quot;, Fname, Lname, Gender)
err := templates.ExecuteTemplate(w, &quot;displayPlayer&quot;, players[0])
if err != nil {
log.Panicln(err)
return
}
}
}
func addPlayer(Fname string, Lname string, Gender string) bool {
if Fname == &quot;&quot; || Lname == &quot;&quot; || Gender == &quot;&quot; {
return false
}
var playerToBeAdded playerType
// Set men to true and women to false
if strings.ToLower(Gender) == &quot;male&quot; {
playerToBeAdded = playerType{Fname, Lname, true}
} else {
playerToBeAdded = playerType{Fname, Lname, false}
}
players = append(players, playerToBeAdded)
return true
}
func main() {
handleFilePath()
http.HandleFunc(&quot;/&quot;, landingPage)
log.Println(&quot;Listening...&quot;)
http.HandleFunc(&quot;/addPlayer&quot;, addPlayerHandler)
err := http.ListenAndServe(&quot;:8081&quot;, nil)
if err != nil {
log.Panicln(err)
}
}

HMTL Templates:
index.html:

{{ define &quot;home&quot; }}
&lt;head xmlns=&quot;http://www.w3.org/1999/html&quot;&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;/assets/home.css&quot;&gt;
&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;title&gt;Home - Match Maker&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;script src=&quot;/assets/home.js&quot;&gt;&lt;/script&gt;
&lt;!-- Button to open the modal login form --&gt;
&lt;button onclick=&quot;document.getElementById(&#39;id01&#39;).style.display=&#39;block&#39;&quot; class=&quot;addPlayer&quot;&gt;Add Player&lt;/button&gt;
&lt;button onclick=&quot;generateGames()&quot;&gt;Generate Games&lt;/button&gt;
&lt;/br&gt;
{{ template &quot;displayPlayer&quot; .}}
&lt;/br&gt;
&lt;!-- The Modal --&gt;
&lt;div id=&quot;id01&quot; class=&quot;modal&quot;&gt;
&lt;form class=&quot;modal-content animate&quot; action=&quot;/&quot; method=&quot;post&quot;&gt;
&lt;div class=&quot;imgcontainer&quot;&gt;
&lt;span onclick=&quot;document.getElementById(&#39;id01&#39;).style.display=&#39;none&#39;&quot; class=&quot;close&quot; title=&quot;Close Modal&quot;&gt;&amp;times;&lt;/span&gt;
&lt;img src=&quot;/assets/be.png&quot; alt=&quot;Avatar&quot; class=&quot;avatar&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;container&quot;&gt;
&lt;label for=&quot;fname&quot; style=&quot;align-content: center&quot;&gt;&lt;b&gt;First Name&lt;/b&gt;&lt;/label&gt;
&lt;input type=&quot;text&quot; placeholder=&quot;John&quot; name=&quot;firstName&quot; required&gt;
&lt;label for=&quot;lname&quot; style=&quot;align-content: center&quot;&gt;&lt;b&gt;Last Name&lt;/b&gt;&lt;/label&gt;
&lt;input type=&quot;text&quot; placeholder=&quot;Smith&quot; name=&quot;lastName&quot; required&gt;
&lt;/div&gt;
&lt;div class=&quot;container&quot;&gt;
Select Gender:
&lt;/br&gt;
&lt;label&gt;
&lt;input type=&quot;radio&quot; name=&quot;gender&quot; value=&quot;male&quot; required&gt;Male
&lt;/label&gt;
&lt;/br&gt;
&lt;label&gt;
&lt;input type=&quot;radio&quot; name=&quot;gender&quot; value=&quot;female&quot;&gt;Female
&lt;/label&gt;
&lt;/div&gt;
&lt;div class=&quot;container&quot; style=&quot;background-color:#f1f1f1; text-align: center&quot;&gt;
&lt;button type=&quot;button&quot; onclick=&quot;document.getElementById(&#39;id01&#39;).style.display=&#39;none&#39;&quot; class=&quot;modelButtons&quot;&gt;
Cancel
&lt;/button&gt;
&lt;button id=&quot;subbtn&quot; type=&quot;submit&quot; class=&quot;modelButtons&quot;
onclick=&quot;submitPlayer(firstName.value, lastName.value, gender.value)&quot;&gt;Submit
&lt;/button&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;script&gt;
// Get the modal
var modal = document.getElementById(&#39;id01&#39;);
// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = &quot;none&quot;;
}
}
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
{{ end }}

displayPlayer.html:

{{ define &quot;displayPlayer&quot; }}
&lt;html lang=&quot;en&quot;&gt;
&lt;body&gt;
{{ .Fname }}
&lt;/br&gt;
{{ .Lname }}
&lt;/br&gt;
{{ .Gender }}
&lt;/body&gt;
&lt;/html&gt;
{{ end }}

Javascript:

home.js:

function submitPlayer(fname, lname, gender) {
if (fname == &quot;&quot; || lname == &quot;&quot; || gender == &quot;&quot;) {
return;
}
$.ajax({
url: &#39;/addPlayer&#39;,
method: &#39;post&#39;,
data: {
fname: fname,
lname: lname,
gender: gender,
},
success: (d) =&gt; {
console.log(&quot;Player Added&quot;);
},
error: (d) =&gt; {
console.log(&quot;An error occurred. Please try again&quot;);
}
});
}
function generateGames() {
$.ajax({
url: &#39;/createGames&#39;,
method: &#39;post&#39;,
success: (d) =&gt; {
console.log(&quot;Generated Games&quot;);
},
error: (d) =&gt; {
console.log(&quot;An error occurred. Please try again&quot;);
}
});
}

答案1

得分: 0

  • home.js移到最后,以便在加载HTML内容到DOM后加载js。
  • 添加了一个包含玩家ID的表格,用于添加addPlayers返回的数据。
  • 删除了submitPlayer
  • 在表单中添加了onSubmit,以防止页面重新加载,因为一旦提交表单,页面就会重新加载,导致丢失addPlayer返回的数据。

index.html

{{ define "home" }}
<head xmlns="http://www.w3.org/1999/html">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/assets/home.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <title>Home - Match Maker</title>
</head>

<body>

<!-- Button to open the modal login form -->
<button onclick="document.getElementById('id01').style.display='block'" class="addPlayer">Add Player</button>

<button onclick="generateGames()">Generate Games</button>

</br>

{{ template "displayPlayer" .}}

</br>

<!-- The Modal -->
<div id="id01" class="modal">
    <form class="modal-content animate" action="/" method="post" onsubmit="return onSubmit(event);">
        <div class="imgcontainer">
            <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">&times;</span>
            <img src="/assets/be.png" alt="Avatar" class="avatar">
        </div>

        <div class="container">
            <label for="fname" style="align-content: center"><b>First Name</b></label>
            <input type="text" placeholder="John" name="firstName" required>

            <label for="lname" style="align-content: center"><b>Last Name</b></label>
            <input type="text" placeholder="Smith" name="lastName" required>
        </div>

        <div class="container">
            Select Gender:
            </br>
            <label>
                <input type="radio" name="gender" value="male" required>Male
            </label>
            </br>
            <label>
                <input type="radio" name="gender" value="female">Female
            </label>
        </div>

        <div class="container" style="background-color:#f1f1f1; text-align: center">
            <button type="button" onclick="document.getElementById('id01').style.display='none'" class="modelButtons">
                Cancel
            </button>
            <button id="subbtn" type="submit" class="modelButtons">Submit
            </button>
        </div>
    </form>
    <div>
      <table id="players"></table>
    </div>
</div>
<script src="/assets/home.js"></script>
<script>
    // Get the modal
    var modal = document.getElementById('id01');

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function (event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
</script>
</body>
</html>
{{ end }}
  • displayPlayer.html更新为表格行格式,以便将其添加到表格中。

displayPlayer.html

{{ define "displayPlayer" }}
<tr>
<td>
{{ .Fname }}
</td>
<td>
{{ .Lname }}
</td>
<td>
{{ .Gender }}
</td>
{{ end }}
  • 将表单数据发送到addPlayer API的函数

home.js

var players = document.querySelector('#players');

function onSubmit(evt) {
  evt.preventDefault()
  let form = evt.target;
  let formData = new FormData(form);
  let fname = formData.get('firstName');
  let lname = formData.get('lastName');
  let gender = formData.get('gender');
  if (fname != "" || lname != "" || gender != "") {
    $.ajax({
        url: '/addPlayer',
        method: 'post',
      data: formData,
      processData: false,
      contentType: false,
        success: (d) => {
          console.log("Player Added", d);
          players.innerHTML += d;
          form.reset();
        },
        error: (d) => {
            console.log("An error occurred. Please try again");
        }
    });
  }

  return false;
}

main.go中的更改

Fname := r.FormValue("firstName")
Lname := r.FormValue("lastName")
Gender := r.FormValue("gender")

# 在返回之前将最后一个添加到切片的元素返回之前总是返回第一个元素
err := templates.ExecuteTemplate(w, "displayPlayer", players[len(players) - 1])
英文:
  • Moved home.js down at the end so js loads after html content are loaded to DOM.
  • Added table with players id to add data returned by addPlayers
  • removed submitPlayer
  • added onSubmit to form so we can prevent page from reloading because as soon we submit form the page reloads causes to lose data returned by addPlayer

index.html

{{ define &quot;home&quot; }}
&lt;head xmlns=&quot;http://www.w3.org/1999/html&quot;&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;/assets/home.css&quot;&gt;
    &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js&quot;&gt;&lt;/script&gt;
    &lt;title&gt;Home - Match Maker&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;!-- Button to open the modal login form --&gt;
&lt;button onclick=&quot;document.getElementById(&#39;id01&#39;).style.display=&#39;block&#39;&quot; class=&quot;addPlayer&quot;&gt;Add Player&lt;/button&gt;

&lt;button onclick=&quot;generateGames()&quot;&gt;Generate Games&lt;/button&gt;

&lt;/br&gt;

{{ template &quot;displayPlayer&quot; .}}

&lt;/br&gt;

&lt;!-- The Modal --&gt;
&lt;div id=&quot;id01&quot; class=&quot;modal&quot;&gt;
    &lt;form class=&quot;modal-content animate&quot; action=&quot;/&quot; method=&quot;post&quot; onsubmit=&quot;return onSubmit(event);&quot;&gt;
        &lt;div class=&quot;imgcontainer&quot;&gt;
            &lt;span onclick=&quot;document.getElementById(&#39;id01&#39;).style.display=&#39;none&#39;&quot; class=&quot;close&quot; title=&quot;Close Modal&quot;&gt;&amp;times;&lt;/span&gt;
            &lt;img src=&quot;/assets/be.png&quot; alt=&quot;Avatar&quot; class=&quot;avatar&quot;&gt;
        &lt;/div&gt;

        &lt;div class=&quot;container&quot;&gt;
            &lt;label for=&quot;fname&quot; style=&quot;align-content: center&quot;&gt;&lt;b&gt;First Name&lt;/b&gt;&lt;/label&gt;
            &lt;input type=&quot;text&quot; placeholder=&quot;John&quot; name=&quot;firstName&quot; required&gt;

            &lt;label for=&quot;lname&quot; style=&quot;align-content: center&quot;&gt;&lt;b&gt;Last Name&lt;/b&gt;&lt;/label&gt;
            &lt;input type=&quot;text&quot; placeholder=&quot;Smith&quot; name=&quot;lastName&quot; required&gt;
        &lt;/div&gt;

        &lt;div class=&quot;container&quot;&gt;
            Select Gender:
            &lt;/br&gt;
            &lt;label&gt;
                &lt;input type=&quot;radio&quot; name=&quot;gender&quot; value=&quot;male&quot; required&gt;Male
            &lt;/label&gt;
            &lt;/br&gt;
            &lt;label&gt;
                &lt;input type=&quot;radio&quot; name=&quot;gender&quot; value=&quot;female&quot;&gt;Female
            &lt;/label&gt;
        &lt;/div&gt;

        &lt;div class=&quot;container&quot; style=&quot;background-color:#f1f1f1; text-align: center&quot;&gt;
            &lt;button type=&quot;button&quot; onclick=&quot;document.getElementById(&#39;id01&#39;).style.display=&#39;none&#39;&quot; class=&quot;modelButtons&quot;&gt;
                Cancel
            &lt;/button&gt;
            &lt;button id=&quot;subbtn&quot; type=&quot;submit&quot; class=&quot;modelButtons&quot;&gt;Submit
            &lt;/button&gt;
        &lt;/div&gt;
    &lt;/form&gt;
    &lt;div&gt;
      &lt;table id=&quot;players&quot;&gt;&lt;/table&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;/assets/home.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
    // Get the modal
    var modal = document.getElementById(&#39;id01&#39;);

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function (event) {
        if (event.target == modal) {
            modal.style.display = &quot;none&quot;;
        }
    }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
{{ end }}
  • Updated displayPlayer.html to table row format so we can add it to table.

displayPlayer.html

{{ define &quot;displayPlayer&quot; }}
&lt;tr&gt;
&lt;td&gt;
{{ .Fname }}
&lt;/td&gt;
&lt;td&gt;
{{ .Lname }}
&lt;/td&gt;
&lt;td&gt;
{{ .Gender }}
&lt;/td&gt;
{{ end }}
  • function to send form data to addPlayer api

home.js

var players = document.querySelector(&#39;#players&#39;);

function onSubmit(evt) {
  evt.preventDefault()
  let form = evt.target;
  let formData = new FormData(form);
  let fname = formData.get(&#39;firstName&#39;);
  let lname = formData.get(&#39;lastName&#39;);
  let gender = formData.get(&#39;gender&#39;);
  if (fname != &quot;&quot; || lname != &quot;&quot; || gender != &quot;&quot;) {
    $.ajax({
        url: &#39;/addPlayer&#39;,
        method: &#39;post&#39;,
      data: formData,
      processData: false,
      contentType: false,
        success: (d) =&gt; {
          console.log(&quot;Player Added&quot;, d);
          players.innerHTML += d;
          form.reset();
        },
        error: (d) =&gt; {
            console.log(&quot;An error occurred. Please try again&quot;);
        }
    });
  }

  return false;
}

Changes in main.go

Fname := r.FormValue(&quot;firstName&quot;)
Lname := r.FormValue(&quot;lastName&quot;)
Gender := r.FormValue(&quot;gender&quot;)

# return the last element added to slice before it was always returning the first element.
err := templates.ExecuteTemplate(w, &quot;displayPlayer&quot;, players[len(players) - 1])

huangapple
  • 本文由 发表于 2021年11月13日 18:16:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/69953328.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定