blocks icon indicating copy to clipboard operation
blocks copied to clipboard

template function for css and js?

Open niklasgrewe opened this issue 2 years ago • 1 comments

Hi @kataras thank you very much for creating the iris framework and blocks. I am new to go but i miss something to get started. I have basic view folder with an index.html like this:

<h1>Index Body</h1>
<h3>Message: {{.Message}}</h3>

<style>
  h1 {
    color: red;
  }

  h3 {
    color: green;
  }
</style>

<script>
  alert('Hello World');
</script>

inside my layouts/main.html file i define the templates css and js like this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{{.Title}}</title>
  {{ template "css" . }}
  {{ template "js" . }}
</head>
<body>
  {{ template "content" . }}
  {{ partial "partials/footer" . }}
</body>
</html>

You can probably already guess what I would like to achieve. The styles and the js code from the index.html should be inserted into the main.html automatically, just like it happens with the content template function.

Is that possible? How can i achieve this? Could blocks support this as well?

niklasgrewe avatar Sep 10 '23 19:09 niklasgrewe

Hello @niklasgrewe, thanks for your kind works, I am still working on the next major upgeade of Iris.

To your question, there is no safe way to automatically parse the styles and script html tags and put it on a define template tag. I believe it's better, and follows the best practises, to put them inside a dynamic css file and render it through the partial func instead.

However, with Blocks, if you use define manually then you can do everything the html/template package let you do.. It does not try to automatically embeds the {{ define "content" }} , so you can write something like this in order to achieve the result you want:

./layouts.main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ if .Title }}{{ .Title }}{{ else }}Default Main Title{{ end }}</title>
    {{ template "styles" . }}
    {{ template "scripts" . }}
</head>
<body>
    {{ template "content" . }}

<footer>{{ partial "partials/footer" .}}</footer>
</body>
</html>

/index.html

{{ define "styles" }}
<style>
    h1 {
      color: red;
    }
  
    h3 {
      color: green;
    }
</style>
{{ end }}

{{ define "scripts" }}
<script>
    alert('Hello World');
</script>
{{ end }}

{{ define "content" }} <!-- MANUALLY -->
<h1>Index Body</h1>
{{ end }}

kataras avatar Dec 14 '24 02:12 kataras