Execute multiple templates in go - go

I have this variable and I wanted to know if I can execute multiple templates
and if I can't do it with this variable then what should I do ?
var (
templates = template.Must(template.ParseGlob("web/Pages/*"))
)
Thanks in advance

You can include templates in other templates by using the {{ template "name" }} action.
Say you have file a.html:
<p>this is A</p>
then you can include it in b.html like this:
{{ template "a.html" }}
<p>this is B</p>
and then if you run templates.ExecuteTemplate(os.Stdout, "b.html", nil) you'll get:
<p>this is A</p>
<p>this is B</p>
See the playground link for a more fleshed out example: https://play.golang.com/p/W0whRWlX119

Related

October CMS and navigation on current page

I am trying to get the basically the active class applied to the current page. As it goes, the builder plugin is setting the URL through:
<a href="{{ detailsPage|page({ (detailsUrlParameter): attribute(record, detailsKeyColumn) }) }}">
However I am new to October so I am not sure how to reference this.page.id in comparison to the url set above.
Basically I want this:
{ set UrlParam = detailsPage|page({ (detailsUrlParameter): attribute(record, detailsKeyColumn) }
{% if this.page.id == UrlParam %} class="active" {% endif %}
Any ideas?
One of the best debugging plugins out there for OctoberCMS is this: https://octobercms.com/plugin/davask-dump
That plugin makes connecting your twig templates to your database / php rendering a breeze.
After installing that plugin you can use {{ d(variable) }} instead of {{ dd(variable) }} and get more information on the array nests etc.
So I would do {{ d(UrlParam) }} and {{ d(this.page.id) }} in your twig template. See what the dump has to say about each of those variables. For clarity I do believe you need the % here {**%** set 'variable' **%**}.
I am also not a fan of the builder component and I use the PHP section on the page / partial pages. And establishing a class with the use function and access the data with $this['variable']. Maybe worth looking into here is a quick example:
Pluginauthor\Plugin\Models\Plugin;
function onStart() {
$plugin = Pluggin::all();
$this['plugin'] = $plugin;
}

Laravel blade creating url

I have a simple problem, basically I am getting name of the website from database and create a link according to it's name. it looks like:
#foreach ($websites as $website)
<a class="websites" href=" {{ asset ($website->name )}}"> {{ asset ($website->name )}}
</a>
#endforeach
Which gives for example: http://localhost/name
Howver links needs to be like this:
http://localhost/website/name how can I add /website into my URL using blade template in laravel?
Try this:
{{ url('website/' . $website->name) }}
This have some improvement on #Laran answer regarding best practices.
You would better use url parameters instead of concatenating the $name parameter
{{ url('website', [$name]) }}
And using named routes will be better to decouple the routing from the views.
// routes/web.php
Route::get('website')->name('website');
and write inside your {{ route('website', [$name]) }}

Golang Accessing Template Variables From Included Templates [duplicate]

This question already has an answer here:
Variable in template's included template
(1 answer)
Closed 6 years ago.
In golang, I am working with three files: index.html, nav.html and main.go
nav.html contains the following:
{{ define "nav" }}
<nav class="nav-container">
<h1>{{ .path }}</h1>
</nav>
{{ end }}
index.html contains the following:
{{ define "index" }}
{{ template "nav" }} <!-- Includes the nav.html file -->
<h1>Welcome to my website. You are visiting {{ .path }}.</h1>
{{ end }}
I am using Golang's template package along with Martini which is not too important in this case.
My main.go file contains:
package main
import (
"net/http"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
)
func main() {
m := martiniSetup()
m.Get("/", func(res http.ResponseWriter, req *http.Request, ren render.Render, params martini.Params) {
parse := make(map[string]interface{})
parse["path"] = req.URL.Path
ren.HTML(http.StatusOK, "index", parse)
})
m.Run()
}
My problem:
The .path variable being parsed into the index template is only accessable by the index template itself.
I include the nav template using {{ template "nav" }} inside index.html. The issue is, nav.html cannot access the .path variable. It is only accessable by the index template.
Is there any way to make the .path variable accessable to all included template files, in my case index.html and nav.html?
You can pass the data to the nested template as an argument like this: {{ template "nav" . }}
Now the dot will be accessible within the define "nav" block.

About Laravel - How to use function string in view

i try to to show data from database article...the content is contain html tags and long text..
so i want make a read more and convert tag html to html view..
this is my code is run :
{{ HTML::decode($show->content) }}
{{ str_limit($show->content, $limit=100, $end=' ...') }}
i try this :
{{ HTML::decode(str_limit($show->content,$limit=100, $end=' ...')) }}
{{ str_limit(HTML::decode($show->content),$limit=100, $end=' ...') }}
but not show ( blank )
annyone can help me to fix it??
thank u b4
Is {{ $show->content }} returning any data to format?
Is your template is .blade?
Maybe it placed somewhere in HTML, where it is not visible?
Try to use this construction with some predefined string to find out if it works. Here is working example:
{{ str_limit('Some big text', $limit = 5, $end='...') }}

Optimising html/template Composition

I'm looking to see if there is a better (faster, more organised) way to split up my templates in Go. I strongly prefer to stick to html/template (or a wrapper thereof) since I trust its security model.
Right now I use template.ParseGlob to parse all of my template files in within init().
I apply template.Funcs to the resulting templates
I set a $title in each template (i.e. listing_payment.tmpl) and pass this to the content template.
I understand that html/template caches templates in memory once parsed
My handlers only call t.ExecuteTemplate(w, "name.tmpl", map[string]interface{}) and don't do any silly parsing on each request.
I compose templates from multiple pieces (and this is the bit I find clunky) as below:
{{ $title := "Page Title" }}
{{ template "head" $title }}
{{ template "checkout" }}
{{ template "top" }}
{{ template "sidebar_details" . }}
{{ template "sidebar_payments" }}
{{ template "sidebar_bottom" }}
<div class="bordered-content">
...
{{ template "listing_content" . }}
...
</div>
{{ template "footer"}}
{{ template "bottom" }}
My three questions are:
Is this performant, or do the multiple {{ template "name" }} tags result in a potential per-request performance hit? I see a lot of write - broken pipe errors when stress testing heavier pages. This might just be due to socket timeouts (i.e. socket closing before the writer can finish) rather than some kind of per-request composition, though (correct me if otherwise!)
Is there a better way to do this within the constraints of the html/template package? The first example in Django's template docs approaches what I'd like. Extend a base layout and replace the title, sidebar and content blocks as needed.
Somewhat tangential: when template.ExecuteTemplate returns an error during a request, is there an idiomatic way to handle it? If I pass the writer to an error handler I end up with soup on the page (because it just continues writing), but a re-direct doesn't seem like idiomatic HTTP.
With some help on Reddit I managed to work out a fairly sensible (and performant) approach to this that allows:
Building layouts with content blocks
Creating templates that effectively "extend" these layouts
Filling in blocks (scripts, sidebars, etc.) with other templates
base.tmpl
<html>
<head>
{{ template "title" .}}
</head>
<body>
{{ template "scripts" . }}
{{ template "sidebar" . }}
{{ template "content" . }}
<footer>
...
</footer>
</body>
index.tmpl
{{ define "title"}}<title>Index Page</title>{{ end }}
// We must define every block in the base layout.
{{ define "scripts" }} {{ end }}
{{ define "sidebar" }}
// We have a two part sidebar that changes depending on the page
{{ template "sidebar_index" }}
{{ template "sidebar_base" }}
{{ end }}
{{ define "content" }}
{{ template "listings_table" . }}
{{ end }}
... and our Go code, which leverages the map[string]*template.Template approach outlined in this SO answer:
var templates map[string]*template.Template
var ErrTemplateDoesNotExist = errors.New("The template does not exist.")
// Load templates on program initialisation
func init() {
if templates == nil {
templates = make(map[string]*template.Template)
}
templates["index.html"] = template.Must(template.ParseFiles("index.tmpl", "sidebar_index.tmpl", "sidebar_base.tmpl", "listings_table.tmpl", "base.tmpl"))
...
}
// renderTemplate is a wrapper around template.ExecuteTemplate.
func renderTemplate(w http.ResponseWriter, name string, data map[string]interface{}) error {
// Ensure the template exists in the map.
tmpl, ok := templates[name]
if !ok {
return ErrTemplateDoesNotExist
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.ExecuteTemplate(w, "base", data)
return nil
}
From initial benchmarks (using wrk) it seems to be a fair bit more performant when it comes to heavy load, likely due to the fact that we're not passing around a whole ParseGlob worth of templates every request. It also makes authoring the templates themselves a lot simpler.

Resources