Unable to load HTML templates from subdirectories with Gin - go

I'm having n issue with loading html files with go gin framework
when i loaded the entire templates folder from the main function its not reading the subdirectories and only read files .
package app
import (
"github.com/gin-gonic/gin"
)
var (
router = gin.Default()
)
func StartApp() {
router.LoadHTMLGlob("templates/*/*.html")
routersMap()
router.Run(":8080")
}
based on the project structure it supposed to show the Loaded HTML Templates as
[GIN-debug] Loaded HTML Templates (2):
- layouts/default.html
- layouts/index.html
- pages/index.html
but actually the output showing this result
[GIN-debug] Loaded HTML Templates (3):
- default.html
- index.html
-
it doesn't even showing the second index.html file
Project Structure

I am also working on learning go and using gin.
I came across this issue also and ran into a few minor issues that i resolved.
I will leave this here in case it may someone else.
Folder layout:
.
├── controllers
│ ├── controller.go
│ └── gui.go
├── html
│ └── templates
│ ├── homepage
│ │ └── index.html
│ ├── layouts
│ │ ├── footer.html
│ │ ├── header.html
│ │ └── menu.html
│ └── views
│ └── library.html
├── models
│ ├── bookstruct.go
│ └── dbconnection.go
├── server.go
└── test
└── server_test.go
The part that is probably needed are these files:
server.go
gui.go
library.html
gui.go
package controllers
import (
"net/http"
"github.com/gin-gonic/gin"
)
...
// BooksView display book library
func BooksView(c *gin.Context) {
c.HTML(
http.StatusOK,
"views/library.html",
gin.H{"title": "Books"},
)
}
library.html
{{ define "views/library.html" }}
<!--Embed the header.html template at this location-->
{{ template "layouts/header.html" .}}
<h1>Hello Books!</h1>
<div>Est nisi debitis recusandae necessitatibus voluptate ut. Laudantium eligendi nostrum quisquam voluptates harum
exercitationem nam harum. Voluptatem sit assumenda sit alias dolores. Modi autem et temporibus impedit qui numquam.
Esse ut recusandae quos deserunt nihil repellendus. Sint et voluptatem quia quia dolor aut.</div>
<div>Est nisi debitis recusandae necessitatibus voluptate ut. Laudantium eligendi nostrum quisquam voluptates harum
exercitationem nam harum. Voluptatem sit assumenda sit alias dolores. Modi autem et temporibus impedit qui numquam.
Esse ut recusandae quos deserunt nihil repellendus. Sint et voluptatem quia quia dolor aut.</div>
<!--Embed the footer.html template at this location-->
{{ template "layouts/footer.html" .}}
{{ end }}
server.go
import (
c "go_first_api/sub_packages/gormrestapi/controllers"
m "go_first_api/sub_packages/gormrestapi/models"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog"
)
// RunServer will run and create a server using gin
func RunServer() {
...
r := gin.Default()
r.LoadHTMLGlob("sub_packages/gormrestapi/html/templates/**/*")
r.GET("/library", c.BooksView)
...
r.Run(":8088")
}
NOTE: main.go is above this sub-dir in the folder path.

See gin#html-rendering,
Using templates with same name in different directories templates/**/*.

Related

How does one include src to a lottie JSON inside an MDX file in a Gatsby project?

For context, I'm running a gatsby site with MDX enabled and I can't for the life of me, figure out how to get the URL to a Lottie JSON animation in the same folder as the MDX file (different from /src/pages/).
I'm not using templates other than rendering every page in the same component using gatsby-browser. The is defined as part of the component and the lottie-player library is included as part of the head.
Here's what I've defined the MDX file as -
---
title: Sample file
slug: /sample
order: 3
type: work
published: true
lastUpdatedDate: September 29, 2022
currentVerion: v2.0.0
excerpt: Sample excerpt text
roles:
- Product Manager
- Product Designer
specialUrl: /blog/foo
coverUrl: ./hero.json
headshot: ./headshot.jpeg
---
export const Head = (props) => <title>{props.pageContext.frontmatter.title + `- Portfolio`}</title>
import { BodyText } from "../../../components/Type"
import { PrimaryButton } from "../../../components/Button"
import HeadshotImg from "./headshot.jpeg"
# Sample project file
<BodyText>{props.pageContext.frontmatter.coverUrl.publicURL}</BodyText>
<BodyText>{props.pageContext.frontmatter.excerpt}</BodyText>
<lottie-player src="/static/23c130bba09d98c90f21287dfc6a9b1c/hero.json" background="transparent" speed="0.5" loop autoplay></lottie-player>
<img src={HeadshotImg} />
<PrimaryButton>Okay so this works</PrimaryButton>
Nihil accusantium aut assumenda est sed[^1]. Enim et eum corporis qui. Modi error laboriosam rerum recusandae impedit voluptate aut distinctio magni. Dolorem voluptatem sit non temporibus quibusdam ipsum. Accusantium voluptatem ut eaque numquam qui numquam est iste.
Voluptate consequatur soluta animi necessitatibus temporibus. Incidunt itaque magni. Eos quisquam similique dolorum occaecati accusantium. Quia voluptatum voluptatem laborum id odit est.
Cum ut non illum est nam ut magni totam. Voluptatibus voluptas magnam mollitia non ut est itaque harum. Et facilis at.
[^1]: Big note.
In the same folder as this MDX file, I've included hero.json. Using a graphQL query, I was able to determine the publicURL underneath the coverUrl object in the schema and included it explicitly here and the lottie renders correctly -
<lottie-player src="/static/23c130bba09d98c90f21287dfc6a9b1c/hero.json" background="transparent" speed="0.5" loop autoplay></lottie-player>
However, I'm not able to use props.pageContext.frontmatter.coverUrl.publicURL directly. This code doesn't display anything. Upon inspecting, there's nothing in between the <p> tags. (BodyText extends the p markup)
<BodyText>{props.pageContext.frontmatter.coverUrl.publicURL}</BodyText>
I tested the excerpt (next line between the <BodyText> tags) and it works correctly too.
What am I missing that the string response retrieved from the graphQL query is good enough for the Lottie src, but when used as a query directly as I do for other frontmatter objects, it doesn't render?
I feel I'm missing something really obvious, but it's taken me 4 hours of trying a lot of things but not getting anywhere. Many thanks in advance!

Range function gives an extra output in my template

I am following this link to figure out how to create an archives page. I am using the hugo-xmin theme with slight modifications.
As far as I understand, range goes through the pages and should print them out. But, I am getting an additional 0001 also. I don't understand why. I'm still a beginner to Hugo and Go.
My output (circled portion in red not what I want)
My archives.html
{{ partial "header.html" . }}
<div class="article-meta">
<h1><span class="title">{{ .Title | markdownify }}</span></h1>
{{ with .Params.author }}<h2 class="author">{{ . }}</h2>{{ end }}
{{ if (gt .Params.date 0) }}<h2 class="date">{{ .Date.Format "2006/01/02" }}</h2>{{ end }}
</div>
<main class="content" role="main">
<div class="inner">
{{ range (.Site.RegularPages.GroupByDate "2006") }}
<h3>{{ .Key }}</h3>
<ul>
{{ range (where .Pages "Type" "post") }}
<li>
<span class="date">{{ .Date.Format "2006/01/02" }}</span>
{{ .Title }}
</li>
{{ end }}
</ul>
{{ end }}
</div>
</main>
{{ partial "footer.html" . }}
My archives.md
---
title: "Archives"
layout: "archives"
draft: false
---
This is archives
My directory structure
.
├── archetypes
│   └── default.md
├── config.toml
├── content
│   ├── about.md
│   ├── archives.md
│   ├── _index.md
│   ├── post
│   │   ├── first_post.md
│   │   ├── sample_code.md
│   │   └── test_math.md
│   └── reading.md
├── data
├── layouts
├── static
└── themes
└── mytheme
├── archetypes
│   └── default.md
├── layouts
│   ├── 404.html
│   ├── archives.html
│   ├── _default
│   │   ├── archives.html
│   │   ├── list.html
│   │   ├── single.html
│   │   └── terms.html
│   ├── index.html
│   └── partials
│   ├── foot_custom.html
│   ├── footer.html
│   ├── head_custom.html
│   └── header.html
├── LICENSE.md
├── static
│   ├── css
│   │   ├── fonts.css
│   │   └── style.css
│   └── js
└── theme.toml
15 directories, 25 files
I changed my archives.html to the following, with some help from hugo-lithium. It works for my use case now. But I still don't understand why the 0001 came up in the first place. So I will not be marking my answer as correct for now.
{{ partial "header.html" . }}
<div class="article-meta">
<h1><span class="title">{{ .Title | markdownify }}</span></h1>
{{ with .Params.author }}<h2 class="author">{{ . }}</h2>{{ end }}
{{ if (gt .Params.date 0) }}<h2 class="date">{{ .Date.Format "2006/01/02" }}</h2>{{ end }}
</div>
{{ range (where .Site.RegularPages "Section" "!=" "").GroupByDate "2006" }}
<h2>{{ .Key }}</h2>
<ul>
{{ range .Pages }}
<li>
<span class="date">{{ .Date.Format "2006/02/02" }}</span>
{{ .Title }}
</li>
{{ end }}
</ul>
{{ end }}
{{ partial "footer.html" . }}

Format (line length) of javadoc (or other) comments

Is there a convention saying how long a line of comment should be?
Different line lengths will not work for any monitor size, or even font size, and other collaborators reading the code will have to scroll back and forth horizontally to read the entire line. I am wondering how this type of stuff is solved in the real world where people collaborate with other coders. Or is there some kind of auto formatter where people can change this kind of stuff on-the-fly to their own taste maybe?
For example:
/**
* Lorem ipsum dolor sit amet, consectetur
* adipisicing elit. Libero pariatur maxime
* praesentium. Similique qui, non aliquam
* nulla libero tenetur voluptatibus delectus,
* ex ab, aspernatur nam animi ipsa. Beatae
**/
versus:
/**
* Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veniam iste magni optio
* impedit rem labore minima cumque quaerat corrupti suscipit dicta, possimus commodi
* laudantium ipsam, tenetur. Omnis qui, veritatis eligendi dignissimos rem quos
* voluptatum quaerat neque at excepturi quod fugit veniam sapiente sunt blanditiis,
* autem illum alias delectus illo, nostrum, dolore aspernatur culpa. Omnis ea deserunt,
* vero odio praesentium repellendus enim recusandae at temporibus officia, obcaecati
**/
(I apologise if this is the wrong stackexchange site to ask this, I honestly didn't know where to put it)

Jekyll: How to place an Include within Markdownified Data?

I'm trying to use Jekyll as a very modular CMS. I've got my index.html file, in which I include 'blocks' of code, like so:
{% include blocks/info.html ref="info" %}
This block defines the HTML structure, and the ref="info" references the data file that defines the content.
This is the block HTML structure:
{% for item in data[include.ref] %}
<li id="jumpTo-{{ item.id }}" class="active">
<h3 class="m-accordion-contentTitle">{{ item.heading }}</h3>
{{ item.text | markdownify }}
</li>
{% endfor %}
And then I have my data file info.yml:
- heading: Setting
id: setting
img-pull: right
text: |
Donec id elit non mi porta gravida at eget metus. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.
{% include blocks/image.html %}
Donec id elit non mi porta gravida at eget metus. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.
Here my text is markdown, that the markdownify plugin takes care of converting into markdown. So my links turn into links, ems turn into ems. Everything is good. Except that my include doesn't work here. It works in a regular markdown.md file - the markdown will get converted properly but the include will also get rendered as HTML. But here the include is just rendered as plain text.
How can I get this include to render as HTML?

Getting started with tabs in Rails app

I was researching here on SO how to implement a tabbed interface in my Rails app. For example, I like how Ryan Bates uses it in his Railscast overview page.
I want to mimic that in my Rails app so that a User's profile has a navigation in it with two or three links. Clicking either link loads information using AJAX (I'm guessing). Then the URL shows /profiles/1/view?info or /profiles/1/view?otherdata
I came across this question, with the following solution:
I would make the contents of each tab be called in by a separate ajax request. This would give you the following benefits
Now each tab can easily be a different view/controller
You only need to load the contents for a tab when it is used; you won't be processing code/downloading html for tabs that the user doesn't use.
The problem is I'm new to Rails and have no idea how to do this. Can anyone point me to some resources that help explain how to set this up? I'd be tabbing between profile data and messages to the user.
Any help would be much appreciated.
As you're new to Rails I'd suggest breaking up your goal into 2 sections: first, get the tabs working with simple content, then add the AJAX.
Step 1 - Getting the tabs working
Have a look at the JQuery UI tabs demos: http://jqueryui.com/demos/tabs/
The code looks something like this:
<div id="tabs">
<ul>
<li>Nunc tincidunt</li>
<li>Proin dolor</li>
<li>Aenean lacinia</li>
</ul>
<div id="tabs-1">
<p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus.</p>
</div>
<div id="tabs-2">
<p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc.</p>
</div>
<div id="tabs-3">
<p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem.</p>
<p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque.</p>
</div>
</div>
<script>
$(function() {
$( "#tabs" ).tabs();
});
</script>
Step 2 - Getting the AJAX working
Check out: http://jqueryui.com/demos/tabs/#ajax
Even it may be hip to use AJAX today, why not do the Simplest Thing That Could Possibly Work? If have done in the past something like the following:
Adding tabs to the UI by code like the following (notation is HAML, sorry for that). As a result, you get a list of links that link to the controllers index action. This code is part of the file layouts/_header.html.haml.
%ul.sideul
- ["page", "notice", "contact"].each do |thing|
- curr = controller.controller_name.singularize == thing
- cl = curr ? 'current' : 'normal'
%li.normal= link_to(thing.humanize, {:controller => controller, :action => "index"}, {:class => cl })
Add then the CSS to your application that this is shown as tabs. There you will need the information if a li is current or normal.
Every time you click then on the tab, the index action of that controller is called, and after that, the index page is shown.
Your file layouts/application.html.haml should have the following content (at least). I have skipped what is not necessary for the example. The template is taken from html5-boilerplate for Rails.
%body{ :class => "#{controller.controller_name}" }
#columns
%header#side
= render "layouts/header"
#main{ :role => 'main' }
%h1= yield(:title)
= render "layouts/flashes"
= yield
= render "layouts/javascripts"
The relevant parts for this solution is:
= render "layouts/header": Renders the list of tabs inside of #columns > header#side
= yield: Renders whatever is in the view for the action of the controller. In our case first the index page, may be later the edit or show page.

Resources