Table of Contents
Question content
Workaround
Home Backend Development Golang What is the difference between running a function in a .go file and calling it in a Go template?

What is the difference between running a function in a .go file and calling it in a Go template?

Feb 09, 2024 pm 12:51 PM
go language

在 .go 文件中运行函数和在 Go 模板中调用它有什么区别?

In the Go language, we can define functions in .go files and call them directly, or we can call functions in Go templates. However, there are some differences in how the function is run and called in both cases. When running a function in a .go file, we can call the function directly through the function name and parameter list. When calling the function in the template, we need to use {{}} syntax to wrap the function call and use the function name as the template directive. part. In addition, function calls in templates can be executed dynamically during template rendering, while when running functions in .go files, the execution of the functions is static and will not be affected by template rendering. Therefore, depending on the specific usage scenarios and needs, we can choose the appropriate way to run functions and call them.

Question content

Using template.funcmap from the text/template package, you can access functions directly from go template files.

Assume the following scenario: In the handler of the user overview page, call the function getallusers and use executetemplate to pass the user object to the template:

func index(w http.responsewriter, r *http.request) {
  users, err := model.getallusers()
  if err != nil {
    render50x()
    return
  }

  data := make(map[string]interface{})
  data["userlist"] = users

  render(w, r, data, "layout", "index")
}
Copy after login

Is this the same as passing a function to the template and executing it there?

var funcs = template.funcmap{
  "getallusers": model.getallusers,
}

// func render
t := template.new("render").funcs(funcs)
if err := template.must(t.parsefs(viewsfs, files...)).executetemplate(w, layout, data); err != nil {
  log.println("error executing template:", err.error())
}

Copy after login
{{ range getAllUsers }}
  {{ .DisplayName }}
{{ end }}
Copy after login

Is there any difference between these two methods?

Workaround

It's the same thing if the function can be called from the template. Some differences:

If you call it in Go, you don't need to register the function. Sometimes you don't have access to template parsing to register a function, so this is the only way (don't forget: you have to register the function before parsing the template).

Additionally, if you call it in Go, you have more "control" over it: you can recover from panics, you can preprocess the results, and you can reuse it in other Go code. You can also choose not to execute the template based on the results, or perform other actions that may not be (easily) expressible in the template.

The result of a function may also not be easily rendered. For example. It may not be string, or it may not have a String() string method. Therefore, some additional (Go) logic may be required to convert the results into a human-readable format, which may not be available in the template, or more functions may need to be registered.

Also note that not all functions can be registered and called from templates. Callable functions can have up to 2 return types, and seconds can only be error. From Go, you can call "any" function and pass only the results you need. If the function has parameters, you must also pass them as data to the template execution (so you can pass them into the template when calling the function).

The above is the detailed content of What is the difference between running a function in a .go file and calling it in a Go template?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

When using sql.Open, why does not report an error when DSN passes empty? When using sql.Open, why does not report an error when DSN passes empty? Apr 02, 2025 pm 12:54 PM

When using sql.Open, why doesn’t the DSN report an error? In Go language, sql.Open...

See all articles