niklaspor / prettier-plugin-go-template Goto Github PK
View Code? Open in Web Editor NEWFixes prettier formatting for go templates 🐹
Home Page: prettier-plugin-go-template-niklaspor.vercel.app
License: MIT License
Fixes prettier formatting for go templates 🐹
Home Page: prettier-plugin-go-template-niklaspor.vercel.app
License: MIT License
In prettier/prettier#6034 (comment), you said:
Only supports: .gohtml, .gotmpl, .go.tmpl, .tmpl, .tpl, .html.tmpl extension to not break other html files in the same repository.
I only have Go Template .html
files in my repo, is there a way to override that support? Or provide prettier a list of globs to run prettier-plugin-go-template
on instead of the standard HTML one!
For example, if we try to format the "Render heading link" markdown render hook example from the documentation, the following error is thrown:
layouts/posts/_markup/render-heading.htmlFormatting failed. SyntaxError: Unexpected closing tag "h01G48S8WZ1SCCTZHN4NWSXMJ4F". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags (1:132)
> 1 | <h01G48S8WZ0FG4HN439Z2D3CW7P id="01G48S8WZ08N4WPEM4W1ZCHF1F">01G48S8WZ0N4AJPJD1NHV9MQ0Y <a href="#01G48S8WZ1QEH9R80VFNDJ4DNE">¶</a></h01G48S8WZ1SCCTZHN4NWSXMJ4F>
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
When formatting
<script></script>
{{ if }}
<script></script>
{{ end }}
I get this error: Error: Encountered unexpted end keyword.
in [email protected]
{{ partial "counts" . }}
{{ if .Params.module }}
{{ $confidence := print "modules/" .Params.module "@" .Params.moduleVersion "/partials/confidence.html" }}
{{ $feedbacks := print "modules/" .Params.module "@" .Params.moduleVersion "/partials/feedbacks.html" }}
{{ $explanation := print "modules/" .Params.module "@" .Params.moduleVersion "/partials/explanation.html" }}
{{ partial $confidence . }}
{{ partial $feedbacks . }}
{{ partial $explanation . }}
{{ else }}
{{ partial "confidence" . }}
{{ partial "feedbacks" . }}
{{ partial "explanation" . }}
{{ end }}
Also I am not sure if this is related, but sometimes it does wrap tags in an unexpected way.
<header>
<a id="close-2" class="back-to-lessons" href="/"
><span
><i class="material-icons" style="max-width:20px; font-size:16px"
>arrow_back_icon</i
>Back to Lessons List</span
></a
>
It's doesn't affect anything, but FYI.
Thanks
Andy
When given:
{{ if }}
<span>1</span>
{{ else if }}
<span>2</span>
{{ else if }}
<s
<span>3</span>
{{ end }}
"prettier-plugin-go-template": "^0.0.12-beta.2",
outputs
❯ yarn format tmp/input.html
yarn run v1.22.18
$ prettier --parser go-template tmp/input.html
tmp/input.htmlFormatting failed. SyntaxError: Unexpected closing tag "span". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags (3:10)
1 |
2 | <s
> 3 | <span>3</span>
| ^^^^^^^
4 |
at y (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/parser-html.js:40:2906)
at Vl (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/parser-html.js:111:2567)
at Xl (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/parser-html.js:111:4116)
at Object.parse (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/parser-html.js:111:4885)
at Object.parse$d [as parse] (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/index.js:12975:19)
at textToDoc (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/index.js:14088:27)
at /Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/index.js:14074:95
at embed (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier-plugin-go-template/lib/index.js:81:18)
at Object.embed (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier-plugin-go-template/lib/index.js:61:24)
at Object.printSubtree (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/index.js:14074:28) {
loc: { start: { line: 3, column: 10 }, end: { line: 3, column: 17 } },
codeFrame: '\x1B[0m \x1B[90m 1 |\x1B[39m\x1B[0m\n' +
'\x1B[0m \x1B[90m 2 |\x1B[39m \x1B[33m<\x1B[39m\x1B[33ms\x1B[39m\x1B[0m\n' +
'\x1B[0m\x1B[31m\x1B[1m>\x1B[22m\x1B[39m\x1B[90m 3 |\x1B[39m \x1B[33m<\x1B[39m\x1B[33mspan\x1B[39m\x1B[33m>\x1B[39m\x1B[35m3\x1B[39m\x1B[33m<\x1B[39m\x1B[33m/\x1B[39m\x1B[33mspan\x1B[39m\x1B[33m>\x1B[39m\x1B[0m\n' +
'\x1B[0m \x1B[90m |\x1B[39m \x1B[31m\x1B[1m^\x1B[22m\x1B[39m\x1B[31m\x1B[1m^\x1B[22m\x1B[39m\x1B[31m\x1B[1m^\x1B[22m\x1B[39m\x1B[31m\x1B[1m^\x1B[22m\x1B[39m\x1B[31m\x1B[1m^\x1B[22m\x1B[39m\x1B[31m\x1B[1m^\x1B[22m\x1B[39m\x1B[31m\x1B[1m^\x1B[22m\x1B[39m\x1B[0m\n' +
'\x1B[0m \x1B[90m 4 |\x1B[39m\x1B[0m'
}
{{ if }}
<span>1</span>
{{ else if }}
<span>2</span>
{{ if }}
<span>1</span>
{{ else if }}
<span>2</span>
{{ else if }}
<s
<span>3</span>
{{ end }}
✨ Done in 0.53s.
And when formatting the resulting output it prints:
input:
{{ if }}
<span>1</span>
{{ else if }}
<span>2</span>
{{ if }}
<span>1</span>
{{ else if }}
<span>2</span>
{{ else if }}
<s
<span>3</span>
{{ end }}
❯ yarn format tmp/formatted.html
yarn run v1.22.18
$ prettier --parser go-template tmp/formatted.html
tmp/formatted.html[error] tmp/formatted.html: Error: Missing end block.
[error] at Object.exports.parseGoTemplate [as parse] (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier-plugin-go-template/lib/parse.js:145:15)
[error] at Object.parse$d [as parse] (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/index.js:12975:19)
[error] at coreFormat (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/index.js:14525:16)
[error] at formatWithCursor$1 (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/index.js:14765:14)
[error] at Object.formatWithCursor (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/index.js:60959:12)
[error] at format$1 (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/bin-prettier.js:18001:21)
[error] at Object.formatFiles$1 [as formatFiles] (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/bin-prettier.js:18115:16)
[error] at async main (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/bin-prettier.js:20216:5)
[error] at async Object.run (/Users/calebjasik-defined/Github/fuzz-prettier-plugin-go-template/node_modules/prettier/bin-prettier.js:20159:5)
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
It seems like it shouldn't be formatting the code if it fails/errors, right?
Im looking for a solution to ignore error or declare in prettierrc that
when they see {{ }} and a $ or a . dot they will just know its from go template
Ive tried your plugins seems not working my usecase still getting an error
this error only happens if used inside an IF statement or using := , functions eq ne ,etc..
Seems like prettier is using the its default for javascript...
Since {} is a javascript entity i think its the main issue there
It would be really useful to setup a way to specify a child parser so that it's possible to use it for hugo templated js file as well as hugo templates HTML or templates json, yaml or xml.
I am using this plugin with hugo and my content pages are written in html
NOT markdown
Problem is prettier is formatting my code when I don't want it to. So I tried following to ignore code
Option1: doesn't work
<!-- prettier-ignore -->
{{< highlight ts "linenos=table" >}}
import styles from './App.module.css';
function App() {
return (
<div className={styles.App}>
<header className={styles.AppHeader}>
{{< / highlight >}}
Option 2: doesn't work
<!-- prettier-ignore-start -->
{{< highlight ts "linenos=table" >}}
import styles from './App.module.css';
function App() {
return (
<div className={styles.App}>
<header className={styles.AppHeader}>
{{< / highlight >}}
<!-- prettier-ignore-end -->
Option 3: doesn't work
<!-- prettier-ignore -->
```ts
import styles from './App.module.css';
function App() {
return (
<div className={styles.App}>
<header className={styles.AppHeader}>
\```
Option 4: doesn't work
<!-- prettier-ignore-start -->
```ts
import styles from './App.module.css';
function App() {
return (
<div className={styles.App}>
<header className={styles.AppHeader}>
\```
<!-- prettier-ignore-end -->
The following option does work but there is annoying prettier ignore comment
{{< highlight ts "linenos=table" >}}
<!-- prettier-ignore -->
import styles from './App.module.css';
function App() {
return (
<div className={styles.App}>
<header className={styles.AppHeader}>
{{< / highlight >}}
above code will generate following snippet that has annoying prettier ignore comment
<!-- prettier-ignore -->
import styles from './App.module.css';
function App() {
return (
<div className={styles.App}>
<header className={styles.AppHeader}>
The plugin correctly realizes that adding certain tags inside of <head>
implicitly closes the <head>
, but incorrectly considers <noscript>
to be a closing tag.
I have a layout file I'm creating for RevealJS presentations. Inside it, I include reveal CSS from a module using templating tags... however, when prettier runs it does a strange transformation to the file. If I just use the normal html parser, nothing happens.
Original file:
<!DOCTYPE html>
<html lang="{{ with .Site.Language }}{{ . }}{{ else }}en-us{{ end }}">
<head>
{{ block "title" . }}
<title>{{ if .IsHome }}{{ $.Site.Title }}{{ else }}{{ .Title }} :: {{ $.Site.Title }}{{ end }}</title>
{{ end }}
<style>
{{ $cssMain := resources.Get "mod/revealjs/dist/reveal.css" | toCSS | minify }}
{{ $cssMain.Content | safeCSS }}
{{ $cssTheme := resources.Get "mod/revealjs/dist/theme/black.css" | toCSS | minify }}
{{ $cssTheme.Content | safeCSS }}
.reveal li:before {
content: none;
}
</style>
</head>
<body>
<div class="reveal">
<div class="slides">
{{- $content := replace .Content "<hr>" "<hr />" -}}
{{- range (split $content "<hr />") -}}
<section>
{{- . | safeHTML -}}
</section>
{{- end -}}
</div>
</div>
{{ partialCached "reveal" . }}
</body>
</html>
If I run bin-prettier.js --parser go-template layouts/presentations/single.html
, I get:
<!DOCTYPE html>
<html lang="{{ with .Site.Language }}{{ . }}{{ else }}en-us{{ end }}">
<head>
{{ block "title" . }}
<title>
{{ if .IsHome }}{{ $.Site.Title }}{{ else }}{{ .Title }} ::
{{ $.Site.Title }}{{ end }}
</title>
{{ end }}
<style>
<!--BPGTBPGT13EPGTEPGT--
> <!--BPGTBPGT14EPGTEPGT--
> <!--BPGTBPGT15EPGTEPGT--
> <!--BPGTBPGT16EPGTEPGT--
> .reveal
li:before {
content: none;
}
</style>
</head>
<body>
<div class="reveal">
<div class="slides">
{{- $content := replace .Content "<hr>" "<hr />" -}}
{{- range (split $content "<hr />") -}}
<section>
{{- . | safeHTML -}}
</section>
{{- end -}}
</div>
</div>
{{ partialCached "reveal" . }}
</body>
</html>
The template functions inside the <style> tags are replaced with commented strings... hashes, maybe? Except they're all the same, so I'm not sure what they're hashes of if they are.
As already mentioned in #19 there were some problems with comments.
While single-line comments are fixed, multi-line comments are reformatted into a single line.
Source:
{{/* 1
2
3
4 */}}
Expected:
{{/* 1
2
3
4 */}}
Actual:
{{/* 1 2 3 4 */}}
First of all thanks for the plugin. I´m trying to configure with html and this is my .prettierrc
file:
{
"printWidth": 80,
"tabWidth": 2,
"trailingComma": "none",
"singleQuote": true,
"overrides": [
{
"files": ["*.html"],
"options": {
"parser": "go-template"
}
}
]
}
VSCode gives me this warning:
Value is not accepted. Valid values: "flow", "babel", "babel-flow", "babel-ts", "typescript", "css", "less", "scss", "json", "json5", "json-stringify", "graphql", "markdown", "mdx", "vue", "yaml", "html", "angular", "lwc".(1)
I am using these versions:
"prettier": "1.19.1",
"prettier-plugin-go-template": "0.0.10",
I also tried last version for prettier. Prettier and plugin are installed locally in the project. I am using Windows 10.
Thanks.
I tried to use this plugin in my Hugo project and I found it could not work with js files well.
In Hugo, there is a feature that Hugo can execute js/css files as a template. FYI, https://gohugo.io/hugo-pipes/resource-from-template/.
But I found that if I used this feature and tried to format my project then it would break. It seems that this plugin did not have support for this, so I was wondering if this would be include in future?
Thank you for making this wonderful plugin! It is very helpful.
This was just released https://github.com/gohugoio/hugo/releases/tag/v0.81.0
Most prominant update on first line of list of all update is now the following is valid.
{{ dict
"country" "Norway"
"population" "5 millions"
"language" "Norwegian"
"language_code" "nb"
"weather" "freezing cold"
"capitol" "Oslo"
"largest_city" "Oslo"
"currency" "Norwegian krone"
"dialing_code" "+47"
}}
Its not super urgent but adding support for this would be nice.
Also just wanted to tell you that I am really loving this pacakge. Only reason I switched to prettier is for word wrap feature. Since I switched to tailwindcss the lines are getting really long and built in VS Code word wrap is failing on me. So any word wrap is very important to me. Like the new feature above.
Many thanks for creating this pacakge.
with
<span>{{ define whatever }}
</span>
{{ end }}
as input, [email protected]
outputs:
<span><span>{{ define whatever }}
</span>
{{ end }}
</span>
adding additional <span>
tags
It doesn't error and return the original text like the invalid
test case does, I think it should probably do so, since I don't see a way to reasonably format it
You recently added acd67e7. In this change, all additional spaces are removed and - more importantly - if there is no space between brackets and code like {{mycode}}
then they are added. But this adjustment also breaks code:
From:
{{- partial "head.html" . -}}
to:
{{ - partial "head.html" . - }}
Which causes an error in hugo: parse failed: template: ...: illegal number syntax: "-"
When giving [email protected]
hello
{{ world }}
formatting it once outputs
hello {{ world }}
and then formatting that output again (imagine you've saved twice in your editor)
hello
{{ world }}
Environments:
Prettier Version: 2.0.4
Running Prettier via: CLI or VSCode plugin
Runtime: Node.js v14.5.0
Operating System: macOS Catalina 10.15.6
Steps to reproduce:
prettier --write ./layouts/_default/list.html
Expected behavior:
To use the plugin and format go (Hugo) html
Actual behavior:
I get an error:
[error] Couldn't resolve parser "go-template"
Attempted fixes
.gohtml
so I assume the issue is with how Prettier sees the config.{
"overrides": [
{
"files": "*.html",
"options": {
"parser": "go-template"
}
}
]
}
YAML
overrides:
- files: "*.html"
options:
parser: "go-template"
I'm still loving this plugin. Thanks so much for your work on this!
I'm noticing an issue when I try to use it on HTML custom elements that include Go templating.
In the following example without any Go template syntax, the prettier-plugin-go template works fine:
<template id="template">
<script>
document.getElementById("demo").innerText = "clicked!";
</script>
<style>
#demo {
font-size: 1.5rem;
}
</style>
<button id="demo">Click me</button>
</template>
If I add templated attributes (the nonce={{ .Nonce }}
attributes), the plugin seems to get confused
<template id="template">
<script nonce="{{ .Nonce }}">
document.getElementById("demo").innerText = "clicked!";
</script>
<style nonce="{{ .Nonce }}">
#demo {
font-size: 1.5rem;
}
</style>
<button id="demo">Click me</button>
</template>
<template id="template"
> <script nonce="{{ .Nonce }}">
document.getElementById("demo").innerText = "clicked!";
</script> <style nonce="{{ .Nonce }}">
#demo {
font-size: 1.5rem;
}
</style>
<button id="demo">Click me</button>
</template>
And then it mostly stops formatting. So if I add lots of whitespace in the <script>
section, the formatter doesn't touch it:
<template id="template"
> <script nonce="{{ .Nonce }}">
document.getElementById("demo").innerText = "clicked!";
</script> <style nonce="{{ .Nonce }}">
#demo {
font-size: 1.5rem;
}
</style>
<button id="demo">Click me</button>
</template>
For this use case, the vanilla Prettier formatter formats the code correctly, so I can work around it by using more targeted matchers in my prettierrc
to prevent prettier-plugin-go-template from handling these files.
Given
<!-- prettier-ignore -->
<span attr="{{ test }}"></span><span attr="{{ test }}">
</span>
as input, [email protected]
outputs
<!-- prettier-ignore -->
<span attr="{{ test }}"></span
><span attr="{{ test }}"> </span>
and so the line that prettier-ignore
was meant to protect is formatted
With the latest update I have found that in some cases running format document
causes a new line to be added in some places over and over again. It seems that this happens below blocks that have been ignored by prettier. I've recorded my screen to demonstrate:
Sorry for the poor quality. But, as you can see, every time I use the "format document" (with prettier selected as my formatter) it is adding an additional new line to that same spot. When I remove the preceding <!-- prettier-ignore -->
statement it stops doing it.
Interestingly, this doesn't happen with anywhere else in this document even though there are similar statements below this one, so there must be something special about that particular section.
Unfortunately this file is part of a private repo, so I can't share access, but here is the entire file for reference:
{{ "<!-- FAQs partial -->" | safeHTML }}
<section id="faq" class="bg-black section faqs responsive-image__bg-section">
{{ $currentProductKey := "" }}
{{ $ctx := . }}
{{ with (cond (eq hugo.Environment "devstore") .Params.devProductId .Params.productId) }}
{{ $currentProductKey = (partialCached "products/get-product-by-id" . . ).key }}
{{ else }}
{{ $ctx = .ctx }}
{{ $currentProductKey = .key }}
{{ end }}
{{ $key := $currentProductKey }}
<!-- prettier-ignore -->
{{ $allFaqsData := (partialCached "get-data" (dict
"ctx" $ctx
"dataFile" "faqs"
) "faqs" ) }}
{{ $faqsData := index $allFaqsData $key }}
{{ partial "site/faqs-structured-data" (dict "faqsdata" $faqsData ) }}
{{ partial "imgix" (dict
"type" "bg"
"image" "/pages/shared/faq-background.jpg"
"alt" ( i18n "faq_background_img_alt" )
"wrapperClass" "responsive-image__bg-wrapper-absolute"
)
}}
<div class="container responsive-image__bg-content">
<!-- prettier-ignore -->
{{ partialCached "page-sections/heading" (dict
"heading" (i18n "frequently_asked_questions")
"isBackgroundDark" true
) "faqs-heading" }}
{{ "<!-- accordion -->" | safeHTML }}
<div id="accordion mx-auto" class="rfs:px-5">
{{ range $faqsData }}
{{ "<!-- accordion item -->" | safeHTML }}
<div>
<button
class="accordion faqsplus focus:ring-0 focus-visible:ring-2 focus-visible:ring-blue-600 active:ring-0"
data-toggle="collapse"
data-target=".collapse{{ with .id }}
{{ (printf ".%v" .) }}
{{ else }}
{{ ( printf ".%v" .ID ) }}
{{ end }}"
data-text="Collapse"
>
{{ .title }}
</button>
<div
id="{{ with .id }}
{{ (printf "%v" .) }}
{{ else }}
{{ ( printf "%v" .ID ) }}
{{ end }}"
class="accordion-panel block collapse {{ with .id }}
{{ (printf "%v" .) }}
{{ else }}
{{ ( printf "%v" .ID ) }}
{{ end }} hidden"
data-parent="#accordion"
>
<div class="accordion-content block__content">
{{ .content | safeHTML }}
</div>
</div>
</div>
{{ end }}
</div>
</div>
<!-- prettier-ignore -->
{{- partialCached "cta-button" (dict
"key" false
"ctx" $ctx
) $ctx.Params.productId $ctx.Section -}}
</section>
{{ "<!-- /FAQs partial -->" | safeHTML }}
I hope this is enough context to be a helpful bug report, but if not I am happy to investigate further and/or provide more information.
EDIT: Found another example of this in action. In the following file new lines are continuously added after line 13: {{ $sources := index (findRE "<section class=\"footnotes\" role=\"doc-endnotes\">" .content) 0 }}
unless <!-- prettier-ignore -->
is removed.
{{ "<!-- footnote-format -->" | safeHTML }}
{{/* This partial is necessary because there is no way to edit footnotes html without modifying the content */}}
{{/* Although the title is footnote-format, we still need to grab the entire content block, including the footnotes, so we can replace them using regex */}}
{{/* This partial modifies content to include footnotes heading */}}
{{/* as well as to add aria attributes to the sources links */}}
<!-- prettier-ignore -->
{{/*****************************************************
Accepted arguments:
- content: (string) [REQUIRED] Content of the page inside of which the pattern will be found and replaced.
*****************************************************/}}
{{ $sources := index (findRE "<section class=\"footnotes\" role=\"doc-endnotes\">" .content) 0 }}
{{ with $sources }}
{{ $sourcesLabeled := print $sources (printf "<h2 class=\"not-sr-only\" id=\"sources-label\">%s</h2>" (i18n "sources_heading")) }}
{{ $noteref := "role=\"doc-noteref\"" }}
{{ $noterefLabeled := print $noteref " aria-describedby=\"sources-label\"" }}
{{ $backlink := "role=\"doc-backlink\"" }}
{{ $backlinkLabeled := print $backlink (printf " aria-label=\"%s\"" (i18n "backlink")) }}
{{ $.content | replaceRE $noteref $noterefLabeled | replaceRE $backlink $backlinkLabeled | replaceRE . $sourcesLabeled | safeHTML }}
{{ else }}
{{ .content | safeHTML }}
{{ end }}
{{ "<!-- /footnote-format -->" | safeHTML }}
Additional info:
"prettier": "^2.3.2",
"prettier-plugin-go-template": "^0.0.11",
"prettier-plugin-packagejson": "^2.2.11",
$ npm version
{
'jbc-marketing-site': '1.0.2',
npm: '7.10.0',
node: '16.0.0',
v8: '9.0.257.17-node.10',
uv: '1.41.0',
zlib: '1.2.11',
brotli: '1.0.9',
ares: '1.17.1',
modules: '93',
nghttp2: '1.42.0',
napi: '8',
llhttp: '6.0.0',
openssl: '1.1.1k+quic',
cldr: '39.0',
icu: '69.1',
tz: '2021a',
unicode: '13.0',
ngtcp2: '0.1.0-DEV',
nghttp3: '0.1.0-DEV'
}
PS: I LOVE the new update! Thank you all so much for this wonderful plugin which makes my life as a Hugo dev 10,000 times better every day!!
Hi
I am using a prettier plugin in visual studio and every once in a while the go-template plugin gets into this state that says.
["ERROR" - 12:36:14 PM] Error formatting document.
Error: Missing ending block.
at Object.preprocess (/home/andy/Development/platform-themes/node_modules/prettier-plugin-go-template/lib/index.js:57:23)
at Object.parse (/home/andy/Development/platform-themes/node_modules/prettier/index.js:13570:21)
at coreFormat (/home/andy/Development/platform-themes/node_modules/prettier/index.js:14851:25)
at format (/home/andy/Development/platform-themes/node_modules/prettier/index.js:15073:14)
at formatWithCursor (/home/andy/Development/platform-themes/node_modules/prettier/index.js:15090:12)
at /home/andy/Development/platform-themes/node_modules/prettier/index.js:54691:12
at Object.format (/home/andy/Development/platform-themes/node_modules/prettier/index.js:54711:12)
at t.default.<anonymous> (/home/andy/.vscode-server/extensions/esbenp.prettier-vscode-5.7.1/dist/extension.js:1:60144)
at Generator.next (<anonymous>)
at s (/home/andy/.vscode-server/extensions/esbenp.prettier-vscode-5.7.1/dist/extension.js:1:54186)
But there is no error in the file and if I restart visual studio it goes away. Then all I get is
["INFO" - 12:40:01 PM] Prettier Options:
{
"filepath": "/home/andy/Development/platform-themes/themes/module-student-template-discovery/layouts/partials/nav.html",
"parser": "go-template",
"useTabs": false,
"tabWidth": 2,
"printWidth": 80
}
["INFO" - 12:40:01 PM] Formatting completed in 142.6453ms.
With the same exact file but having restarted visual studio.
Not quite sure how to "debug" the actual problem. Suggestions? I was thinking of putting some random logging into the code, but didn't really know where to start.
Thanks
Andy
I'm not sure whether this is intended, but upgrading to v0.0.11 wants to make these changes:
https://github.com/jasikpark/jasik-xyz/commit/fe3f475d4f7903b1ba2d464b50e9d73989f258c9
It seems like a regression maybe? It definitely makes more sense to me for the <script>
tags to start on their own lines, right?
["INFO" - 11:07:19 PM] Detected local configuration (i.e. .prettierrc or .editorconfig), VS Code configuration will not be used
["INFO" - 11:07:19 PM] Prettier Options:
{
"filepath": "/Users/jensamunch/Documents/website-v6/layouts/partials/book-a-demo.html",
"parser": "go-template"
}
["ERROR" - 11:07:19 PM] Error formatting document.
["ERROR" - 11:07:19 PM] Couldn't resolve parser "go-template"
Error: Couldn't resolve parser "go-template"
at resolveParser (/Users/jensamunch/.vscode/extensions/esbenp.prettier-vscode-5.1.3/node_modules/prettier/index.js:11343:15)
at normalize$1 (/Users/jensamunch/.vscode/extensions/esbenp.prettier-vscode-5.1.3/node_modules/prettier/index.js:11438:18)
at formatWithCursor (/Users/jensamunch/.vscode/extensions/esbenp.prettier-vscode-5.1.3/node_modules/prettier/index.js:15034:12)
at /Users/jensamunch/.vscode/extensions/esbenp.prettier-vscode-5.1.3/node_modules/prettier/index.js:51620:12
at Object.format (/Users/jensamunch/.vscode/extensions/esbenp.prettier-vscode-5.1.3/node_modules/prettier/index.js:51640:12)
at t.default. (/Users/jensamunch/.vscode/extensions/esbenp.prettier-vscode-5.1.3/dist/extension.js:1:58387)
at Generator.next ()
at s (/Users/jensamunch/.vscode/extensions/esbenp.prettier-vscode-5.1.3/dist/extension.js:1:53305)
["INFO" - 11:07:19 PM] Formatting completed in 14.902095ms.
in youtube.html
, I had code duplicated...
before:
{{- $pc := .Page.Site.Config.Privacy.YouTube -}}
{{- if not $pc.Disable -}}
{{- $ytHost := cond $pc.PrivacyEnhanced "www.youtube-nocookie.com" "www.youtube.com" -}}
{{- $id := .Get "id" | default (.Get 0) -}}
{{- $class := .Get "class" | default (.Get 1) -}}
{{- $lazy := .Get "lazy" | default (.Get 2) -}}
{{- $title := .Get "title" | default "YouTube Video" -}}
{{- if not $lazy }}
<div
{{ with $class }}
class="{{ . }}"
{{ else }}
style="position: relative; padding-bottom: 56.25%; height: 0; overflow:
hidden;"
{{ end }}
>
<iframe
src="https://{{ $ytHost }}/embed/{{ $id }}{{ with .Get "autoplay" }}
{{ if eq . "true" }}?autoplay=1{{ end }}
{{ end }}"
{{ if not $class }}
style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;
border:0;"
{{ end }}allowfullscreen
title="{{ $title }}"
></iframe>
</div>
{{ else }}
<div
class="lazyframe"
data-vendor="youtube_nocookie"
data-title=""
data-thumbnail=""
data-src="https://{{ $ytHost }}/embed/{{ $id }}"
data-ratio="1:1"
data-initinview="false"
{{ with .Get "autoplay" }}
{{ if eq . "true" }}data-autoplay="true"{{ else }}data-autoplay="false"{{ end }}
{{ end }}"
></div>
<script type="module" src="js/lazyframe.js" />
{{ end -}}
{{ end -}}
after:
{{- $pc := .Page.Site.Config.Privacy.YouTube -}}
{{- if not $pc.Disable -}}
{{- $ytHost := cond $pc.PrivacyEnhanced "www.youtube-nocookie.com" "www.youtube.com" -}}
{{- $id := .Get "id" | default (.Get 0) -}}
{{- $class := .Get "class" | default (.Get 1) -}}
{{- $lazy := .Get "lazy" | default (.Get 2) -}}
{{- $title := .Get "title" | default "YouTube Video" -}}
{{- if not $lazy }}
<div
{{ with $class }}
class="{{ . }}"
{{ else }}
style="position: relative; padding-bottom: 56.25%; height: 0; overflow:
hidden;"
{{ end }}
>
<iframe
src="https://{{ $ytHost }}/embed/{{ $id }}{{ with .Get "autoplay" }}
{{ if eq . "true" }}?autoplay=1{{ end }}
{{ end }}"
{{ if not $class }}
style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;
border:0;"
{{ end }}allowfullscreen
title="{{ $title }}"
></iframe>
</div>
{{- $pc := .Page.Site.Config.Privacy.YouTube -}}
{{- if not $pc.Disable -}}
{{- $ytHost := cond $pc.PrivacyEnhanced "www.youtube-nocookie.com" "www.youtube.com" -}}
{{- $id := .Get "id" | default (.Get 0) -}}
{{- $class := .Get "class" | default (.Get 1) -}}
{{- $lazy := .Get "lazy" | default (.Get 2) -}}
{{- $title := .Get "title" | default "YouTube Video" -}}
{{- if not $lazy }}
<div
{{ with $class }}
class="{{ . }}"
{{ else }}
style="position: relative; padding-bottom: 56.25%; height: 0; overflow:
hidden;"
{{ end }}
>
<iframe
src="https://{{ $ytHost }}/embed/{{ $id }}{{ with .Get "autoplay" }}
{{ if eq . "true" }}?autoplay=1{{ end }}
{{ end }}"
{{ if not $class }}
style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;
border:0;"
{{ end }}allowfullscreen
title="{{ $title }}"
></iframe>
</div>
{{ else }}
<div
class="lazyframe"
data-vendor="youtube_nocookie"
data-title=""
data-thumbnail=""
data-src="https://{{ $ytHost }}/embed/{{ $id }}"
data-ratio="1:1"
data-initinview="false"
{{ with .Get "autoplay" }}
{{ if eq . "true" }}data-autoplay="true"{{ else }}data-autoplay="false"{{ end }}
{{ end }}"
></div>
<script type="module" src="js/lazyframe.js" />
{{ end -}}
{{ end -}}
{{ end -}}
If I have a template command that uses quotation marks inside of an HTML attribute, like <div data-x='{{ doThing "whatever" }}'>
, I like for the outer quotation marks to be a single quote '
so that my text editor (which doesn't know about Go templates) highlights the block semi-correctly, but the plugin changes it to be a double quote "
.
Input
{{ if not .Lastmod.IsZero }}<meta property="article:modified_time" content="{{ .Lastmod.Format "2006-01-02T15:04:05-07:00" | safeHTML }}">{{ end }}
Output
{{ if not .Lastmod.IsZero }}
<meta property="article:modified_time" content="{{ .Lastmod.Format "2006-01-02T15:04:05-07:00" | safeHTML }}"
/>{{ end }}
{{ end }}
is now misaligned with {{ if ... }}
which can give the appearance that the rest of the file is within the IF statement.
Line Width Setting
printWidth: 120
Version: 0.0.10
Right now the formatter indents else/else if
blocks one level deeper than their containing if, which is so confusing I assumed it was a bug, but I see in #9 that it was deliberate, which is frankly even more confusing. Is there actually any other language with a standard format where you indent the else statement to a different level its associated if block?
In any case, is it possible to get an option or a flag so if
and else
blocks are indented to the same level?
I've got this error while reformat using prettier on Hugo HTML document.
["INFO" - 7:41:36 PM] Extension Name: esbenp.prettier-vscode.
["INFO" - 7:41:36 PM] Extension Version: 9.5.0.
["INFO" - 7:41:42 PM] File Info:
{
"ignored": false,
"inferredParser": "go-template"
}
["ERROR" - 9:41:22 PM] Error formatting document.
["ERROR" - 9:41:22 PM] An error occured during printing. Found invalid node block.
Error: An error occured during printing. Found invalid node block.
at Object.print (/usr/local/lib/node_modules/prettier-plugin-go-template/src/index.ts:89:13)
at callPluginPrintFunction (/usr/local/lib/node_modules/prettier/index.js:8447:26)
My VSCode settings:
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"prettier.prettierPath": "/usr/local/lib/node_modules/prettier"
When [email protected]
is given:
it first formats it as
and on a second format as
Is #
a valid beginning to some go template clause? It reads to me like this should be an error, but I'm unsure...
The following minimal example code ...
{{ if .url }}<a href="{{ .url }}">{{ end }}
<span>Content</span>
{{ if .url }}</a>{{ end }}
... duplicates to the following upon format:
{{ if .url }}<a href="{{ .url }}"></a>{{ end }}
<span>Content</span>
{{ if .url }}<a href="{{ .url }}">{{ end }}
<span>Content</span>
{{ if .url }}</a>{{ end }}
My current workaround is this:
<!-- prettier-ignore -->
{{ if .url }}<a href="{{ .url }}">{{ end }}
<span>Content</span>
<!-- prettier-ignore -->
{{ if .url }}</a>{{ end }}
Not sure if options are on the table for this module, but I'd like to see one to remove the space here:
prettier-plugin-go-template/src/index.ts
Lines 50 to 51 in 76ed143
meaning it should output {{.var}}
instead of {{ .var }}
for people who prefer terseness.
This seems like a fantastic project, thanks for implementing it.
I am more of a backend Go developer, and try to stay away from NPM/Yarn, Rollup, etc, etc
It would be really wonderful if this was part of Prettier, and
so every VSCode user could this plugin without having to touch NPM.
Just by using a standard VScode extension:
https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode
(NPM is great, until you do something wrong, and you don't know how to fix it)
Maybe it is not meant to be due to do logistical reasons, but I wanted to throw it out there,
in case.
Currently debugging running npm install
after cloning this project - I'm not sure what this error is:
gitpod /workspace/prettier-plugin-go-template (master) $ npm i
npm ERR! code ECONNREFUSED
npm ERR! syscall connect
npm ERR! errno ECONNREFUSED
npm ERR! FetchError: request to http://localhost:4873/@types%2fprettier/-/prettier-2.2.3.tgz failed, reason: connect ECONNREFUSED 127.0.0.1:4873
npm ERR! at ClientRequest.<anonymous> (/home/gitpod/.nvm/versions/node/v16.13.2/lib/node_modules/npm/node_modules/minipass-fetch/lib/index.js:110:14)
npm ERR! at ClientRequest.emit (node:events:390:28)
npm ERR! at Socket.socketErrorListener (node:_http_client:447:9)
npm ERR! at Socket.emit (node:events:402:35)
npm ERR! at emitErrorNT (node:internal/streams/destroy:157:8)
npm ERR! at emitErrorCloseNT (node:internal/streams/destroy:122:3)
npm ERR! at processTicksAndRejections (node:internal/process/task_queues:83:21)
npm ERR! FetchError: request to http://localhost:4873/@types%2fprettier/-/prettier-2.2.3.tgz failed, reason: connect ECONNREFUSED 127.0.0.1:4873
npm ERR! at ClientRequest.<anonymous> (/home/gitpod/.nvm/versions/node/v16.13.2/lib/node_modules/npm/node_modules/minipass-fetch/lib/index.js:110:14)
npm ERR! at ClientRequest.emit (node:events:390:28)
npm ERR! at Socket.socketErrorListener (node:_http_client:447:9)
npm ERR! at Socket.emit (node:events:402:35)
npm ERR! at emitErrorNT (node:internal/streams/destroy:157:8)
npm ERR! at emitErrorCloseNT (node:internal/streams/destroy:122:3)
npm ERR! at processTicksAndRejections (node:internal/process/task_queues:83:21) {
npm ERR! code: 'ECONNREFUSED',
npm ERR! errno: 'ECONNREFUSED',
npm ERR! syscall: 'connect',
npm ERR! address: '127.0.0.1',
npm ERR! port: 4873,
npm ERR! type: 'system'
npm ERR! }
npm ERR!
npm ERR! If you are behind a proxy, please make sure that the
npm ERR! 'proxy' config is set properly. See: 'npm help config'
npm ERR! A complete log of this run can be found in:
npm ERR! /home/gitpod/.npm/_logs/2022-03-05T21_07_03_751Z-debug.log
Thanks so much for your work on this project! It's a great improvement to my dev workflow.
Is it possible to make financial contributions to the project?
Consider adding a file called .github/FUNDING.yml
that shows people how they can donate.
It can be as simple as:
custom: ["https://www.paypal.me/your-paypal-address"]
Support for newlines within actions and pipelines was added in Go version 1.16 and Hugo release 0.81.
It would be useful if the format was kept or converted correctly.
This:
{{ dict
"country" "Norway"
"population" "5 millions"
}}
is converted to:
{{ dict"country" "Norway""population" "5 millions"}}
Some spaces are needed. 👀
Keep the formatting or (preferably) convert it to a line with the appropriate spaces.
{{ dict "country" "Norway" "population" "5 millions"}}
In longer strings, when multiple lines are kept, this problem does not occur and the formatting is set correctly.
Something like this, no problem.
{{ dict
"country" "Norway"
"population" "5 millions"
"language" "Norwegian"
"dialing_code" "+47"
}}
Thanks for this plugin! I found it thanks to your comment and now I'm able to use Prettier + your parser to format go templates! I have just tried it out (removing all the <!-- prettier-ignore -->
directives I had in my code) and it works really well! 😊
These are the issues I have found in my codebase (before/after formatting with go-template), just in case you'd be open to addressing them. Thanks again!
<meta property="og:url" content="{{ strings.TrimSuffix "/" .Permalink }}" />
<meta property="og:url" content="
{{ strings.TrimSuffix "/" .Permalink }}
" />
<p class="copyright">
© 2020 {{ .Site.Title }}. All rights reserved.
</p>
<p class="copyright">
© 2020
{{ .Site.Title }}. All rights reserved.
</p>
<a class="image fit">
<img src="{{ partial "get-img-src.html" (dict "image" "my-image.jpg" "context" .) }}" alt="My image" />
</a>
<a class="image fit"> <img src="{{ partial "get-img-src.html" (dict "image" "my-image.jpg" "context" .) }}" alt="My image" /> </a>
We're using the go-templates prettier setup and it work 99% of the time, but every once in a while it will convert.
<script type="text/javascript">
{{ $data.script | safeJS }}
</script>
to
<script type="text/javascript">
{
{
$data.script | safeJS;
}
}
</script>
At seemingly random times. Something is triggering it to do the wrong thing but only very few occasions.
Not sure what to attribute it to.
<link rel="preload" as="style" {{ printf "href=\"https://fonts.googleapis.com/css2?%s&display=swap\"" . | safeHTMLAttr }}>
is converted to
<link rel="preload" as="style" <!--BPGT<!--BPGT<!--BPGTBPGT119EPGTEPGT-- />EPGT-- />EPGT-- /> />
Docs: https://gohugo.io/functions/safehtmlattr/
Note #24 reports a similar but different issue (it's unrelated to safeHTMLAttr
). Perhaps when #24 is resolved, it might also resolve this one though.
Version: 0.0.10
Looks like prettier-plugin-go-template
doesn't work with pnpm
package manager, or I did something wrong.
When I try to call prettier
, I got this error Couldn't resolve parser "go-template"
.
My pacakge.json
:
{
"name": "pnpm-prettier-go-template",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "hugo server -D",
"prettier": "prettier --config .prettierrc.js \"./themes/**/{*.ts,*.html,*.scss}\" --check"
},
"author": "",
"license": "ISC",
"devDependencies": {
"prettier": "2.5.1",
"prettier-plugin-go-template": "0.0.11"
}
}
My .prettierrc.js
:
module.exports = {
proseWrap: 'never',
parser: 'typescript',
tabWidth: 2,
useTabs: false,
singleQuote: true,
trailingComma: 'none',
bracketSpacing: true,
arrowParens: 'always',
semi: true,
printWidth: 120,
endOfLine: 'lf',
overrides: [
{
files: ['*.html'],
options: {
parser: 'go-template'
}
}
],
};
Repo to reproduce: https://github.com/abramovslava/prettier-go-template-pnpm-issue
Thanks.
Hi @NiklasPor,
Please consider about the indent of {{ }}
inside of html code.
I looked inside your test case, seems it's not cover with indent of {{ }}
yet.
How do you think?
{
name: "No Unnecessary Newlines",
code: `{{ $sassOptions := (dict "targetPath" "css/main.css" "outputStyle" (cond .Site.Params.Minify "compressed" "expanded") "enableSourceMap" (not hugo.IsProduction)) }}
{{ $css := resources.Match "sass/*.scss" | resources.Concat "" | resources.ExecuteAsTemplate "" . | toCSS $sassOptions }}
{{ if $.Site.Params.Minify }}
{{ $css = $css | fingerprint "sha512" }}
{{ end }}
<link rel="stylesheet" href="{{ $css.RelPermalink }}" integrity="{{ $css.Data.Integrity }}" />
<link rel="preconnect" href="https://www.google-analytics.com" />
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-160619965-1"></script>
{{ $analytics := resources.Get "js/analytics.js" | babel (dict "config" "babel.config.json" "verbose" true) | minify | fingerprint "sha512" }}
{{ if ne $analytics.Data.Integrity "sha512-0LVjmruu9Umzscdy8OR21j2JModpt/NfJnMnR82jGVQXBeamQnJMZIw97GTyxA/Ul0rjS8wfva5wcAPedlE+Zw==" }}
{{ errorf "analytics.js has a new SHA: %q" $analytics.Data.Integrity }}
{{ end }}
<script>
{{ $analytics.Content | safeJS }}
</script>
`,
expectedCode: `{{ $sassOptions := (dict "targetPath" "css/main.css" "outputStyle" (cond .Site.Params.Minify "compressed" "expanded") "enableSourceMap" (not hugo.IsProduction)) }}
{{ $css := resources.Match "sass/*.scss" | resources.Concat "" | resources.ExecuteAsTemplate "" . | toCSS $sassOptions }}
{{ if $.Site.Params.Minify }}
{{ $css = $css | fingerprint "sha512" }}
{{ end }}
<link
rel="stylesheet"
href="{{ $css.RelPermalink }}"
integrity="{{ $css.Data.Integrity }}"
/>
<link rel="preconnect" href="https://www.google-analytics.com" />
<script
async
src="https://www.googletagmanager.com/gtag/js?id=UA-160619965-1"
></script>
{{ $analytics := resources.Get "js/analytics.js" | babel (dict "config" "babel.config.json" "verbose" true) | minify | fingerprint "sha512" }}
{{ if ne $analytics.Data.Integrity "sha512-0LVjmruu9Umzscdy8OR21j2JModpt/NfJnMnR82jGVQXBeamQnJMZIw97GTyxA/Ul0rjS8wfva5wcAPedlE+Zw==" }}
{{ errorf "analytics.js has a new SHA: %q" $analytics.Data.Integrity }}
{{ end }}
<script>
{{ $analytics.Content | safeJS }}
</script>
`,
},```
{{/* .... */}}
gets reformatted as a command {{ /* .... */ }}
breaking hugo.
Hi! Thanks again for this plugin! 😊
I'm seeing the following formatting issues in my codebase:
<a class="image fit">
<img src="{{ partial "get-img-src.html" (dict "image" "my-image.jpg" "context" .) }}" alt="My image" />
</a>
<a class="image fit"> <img src="{{ partial "get-img-src.html" (dict "image" "my-image.jpg" "context" .) }}" alt="My image" /> </a>
<meta property="twitter:url" content="{{ strings.TrimSuffix "/" .Permalink }}" />
<meta property="twitter:url" content="
{{ strings.TrimSuffix "/" .Permalink }}
" />
<link rel="apple-touch-icon" sizes="180x180" href="{{ (resources.Get "apple-touch-icon.png" | fingerprint).RelPermalink }}" />
<link rel="icon" type="image/x-icon" href="{{ (resources.Get "favicon.ico" | fingerprint).RelPermalink }}" />
<link rel="icon" type="image/png" sizes="32x32" href="{{ (resources.Get "favicon-32x32.png" | fingerprint).RelPermalink }}" />
<link rel="icon" type="image/png" sizes="194x194" href="{{ (resources.Get "favicon-194x194.png" | fingerprint).RelPermalink }}" />
<link rel="icon" type="image/png" sizes="192x192" href="{{ (resources.Get "android-chrome-192x192.png" | fingerprint).RelPermalink }}" />
<link rel="icon" type="image/png" sizes="16x16" href="{{ (resources.Get "favicon-16x16.png" | fingerprint).RelPermalink }}" />
<link rel="manifest" href="{{ (resources.Get "site.webmanifest" | resources.ExecuteAsTemplate "" . | minify | fingerprint).RelPermalink }}" />
<link rel="mask-icon" href="{{ (resources.Get "safari-pinned-tab.svg" | minify | fingerprint).RelPermalink }}" color="white" />
<link rel="apple-touch-icon" sizes="180x180" href="
{{ (resources.Get "apple-touch-icon.png" | fingerprint).RelPermalink }}
" /> <link rel="icon" type="image/x-icon" href="
{{ (resources.Get "favicon.ico" | fingerprint).RelPermalink }}
" /> <link rel="icon" type="image/png" sizes="32x32" href="
{{ (resources.Get "favicon-32x32.png" | fingerprint).RelPermalink }}
" /> <link rel="icon" type="image/png" sizes="194x194" href="
{{ (resources.Get "favicon-194x194.png" | fingerprint).RelPermalink }}
" /> <link rel="icon" type="image/png" sizes="192x192" href="
{{ (resources.Get "android-chrome-192x192.png" | fingerprint).RelPermalink }}
" /> <link rel="icon" type="image/png" sizes="16x16" href="
{{ (resources.Get "favicon-16x16.png" | fingerprint).RelPermalink }}
" /> <link rel="manifest" href="
{{ (resources.Get "site.webmanifest" | resources.ExecuteAsTemplate "" . | minify | fingerprint).RelPermalink }}
" /> <link rel="mask-icon" href="
{{ (resources.Get "safari-pinned-tab.svg" | minify | fingerprint).RelPermalink }}
" color="white" />
{{ $sassOptions := (dict "targetPath" "css/main.css" "outputStyle" (cond .Site.Params.Minify "compressed" "expanded") "enableSourceMap" (not hugo.IsProduction)) }}
{{ $css := resources.Match "sass/*.scss" | resources.Concat "" | resources.ExecuteAsTemplate "" . | toCSS $sassOptions }}
{{ if $.Site.Params.Minify }}
{{ $css = $css | fingerprint "sha512" }}
{{ end }}
<link rel="stylesheet" href="{{ $css.RelPermalink }}" integrity="{{ $css.Data.Integrity }}" />
<link rel="preconnect" href="https://www.google-analytics.com" />
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-160619965-1"></script>
{{ $analytics := resources.Get "js/analytics.js" | babel (dict "config" "babel.config.json" "verbose" true) | minify | fingerprint "sha512" }}
{{ if ne $analytics.Data.Integrity "sha512-0LVjmruu9Umzscdy8OR21j2JModpt/NfJnMnR82jGVQXBeamQnJMZIw97GTyxA/Ul0rjS8wfva5wcAPedlE+Zw==" }}
{{ errorf "analytics.js has a new SHA: %q" $analytics.Data.Integrity }}
{{ end }}
<script>
{{ $analytics.Content | safeJS }}
</script>
{{ $sassOptions := (dict "targetPath" "css/main.css" "outputStyle" (cond .Site.Params.Minify "compressed" "expanded") "enableSourceMap" (not hugo.IsProduction)) }}
{{ $css := resources.Match "sass/*.scss" | resources.Concat "" | resources.ExecuteAsTemplate "" . | toCSS $sassOptions }}
{{ if $.Site.Params.Minify }}
{{ $css = $css | fingerprint "sha512" }}
{{ end }}
<link rel="stylesheet" href="{{ $css.RelPermalink }}" integrity="{{ $css.Data.Integrity }}" />
<link rel="preconnect" href="https://www.google-analytics.com" />
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-160619965-1"></script>
{{ $analytics := resources.Get "js/analytics.js" | babel (dict "config" "babel.config.json" "verbose" true) | minify | fingerprint "sha512" }}
{{ if ne $analytics.Data.Integrity "sha512-0LVjmruu9Umzscdy8OR21j2JModpt/NfJnMnR82jGVQXBeamQnJMZIw97GTyxA/Ul0rjS8wfva5wcAPedlE+Zw==" }}
{{ errorf "analytics.js has a new SHA: %q" $analytics.Data.Integrity }}
{{ end }}
<script>
{{ $analytics.Content | safeJS }}
</script>
Thanks!
Related: #1
When trying to format this code
<head>
{{ if eq .Page.Section "card" }}
<meta name="robots" content="noindex" />
{{ else }}
<meta name="robots" content="max-image-preview:large" />
{{ end }}
</head>
gets reformatted as
<head>
{{ if eq .Page.Section "card" }}>
<meta name="robots" content="noindex" /
{{ else }}
<meta name="robots" content="max-image-preview:large" /
{{ end }}>
</head>
A >
is added then the first }}
From then on everything is distorted.
I attach the console output after applying JsPrettier Format Code:
output-console.txt
And all the files from the test project:
test-project.zip
Hello, when I try to format a document I get this error:
["ERROR" - 2:29:42 PM] Error formatting document.
["ERROR" - 2:29:42 PM] Couldn't resolve parser "go-template"
Error: Couldn't resolve parser "go-template"
at resolveParser$1 (c:\Users\user\.vscode\extensions\esbenp.prettier-vscode-8.0.1\node_modules\prettier\index.js:13626:13)
at normalize$1 (c:\Users\user\.vscode\extensions\esbenp.prettier-vscode-8.0.1\node_modules\prettier\index.js:13721:18)
at formatWithCursor$1 (c:\Users\user\.vscode\extensions\esbenp.prettier-vscode-8.0.1\node_modules\prettier\index.js:15404:46)
at c:\Users\user\.vscode\extensions\esbenp.prettier-vscode-8.0.1\node_modules\prettier\index.js:60171:12
at Object.format (c:\Users\user\.vscode\extensions\esbenp.prettier-vscode-8.0.1\node_modules\prettier\index.js:60191:12)
at t.default.<anonymous> (c:\Users\user\.vscode\extensions\esbenp.prettier-vscode-8.0.1\dist\extension.js:1:14555)
at Generator.next (<anonymous>)
at i (c:\Users\user\.vscode\extensions\esbenp.prettier-vscode-8.0.1\dist\extension.js:1:7003)
["INFO" - 2:29:42 PM] Formatting completed in 14.9331ms.
I've installed dependencies globally
npm list -g --depth=0
+-- [email protected]
+-- [email protected]
`-- [email protected]
Any ideas?
I wasn't sure where to put this, but when using the latest beta version it's no longer recognizing the {{ end }} in some cases.
Version 0.0.11-beta
This file for example (gallery.html inside of hugo)
<div class="article-gallery">
<div class="article-gallery-photos">
{{ range .Params }}
<a class="article-gallery-img fancybox" href="{{ . }}" rel="group1">
<img src="{{ . | relURL }}" itemprop="image" />
</a>
{{ end }}
</div>
</div>
Will cause the following error:
["ERROR" - 10:35:18 AM] Unexpected closing tag "BPGTundefinedEPGT". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags (7:5)
5 | <img src="BPGT3EPGT" itemprop="image" />
6 | </a>
> 7 | </BPGTundefinedEPGT>
| ^
8 | </div>
9 | </div>
SyntaxError: Unexpected closing tag "BPGTundefinedEPGT". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags (7:5)
5 | <img src="BPGT3EPGT" itemprop="image" />
6 | </a>
> 7 | </BPGTundefinedEPGT>
| ^
8 | </div>
9 | </div>
at Ft (/home/ubuntu/platform-themes/themes/module-student-template-cme@feature-data-builds/node_modules/prettier/parser-html.js:1:52073)
at ps (/home/ubuntu/platform-themes/themes/module-student-template-cme@feature-data-builds/node_modules/prettier/parser-html.js:113:2319)
at e (/home/ubuntu/platform-themes/themes/module-student-template-cme@feature-data-builds/node_modules/prettier/parser-html.js:113:4291)
at Object.parse (/home/ubuntu/platform-themes/themes/module-student-template-cme@feature-data-builds/node_modules/prettier/parser-html.js:113:4830)
at Object.parse (/home/ubuntu/platform-themes/themes/module-student-template-cme@feature-data-builds/node_modules/prettier/index.js:13565:19)
at coreFormat (/home/ubuntu/platform-themes/themes/module-student-template-cme@feature-data-builds/node_modules/prettier/index.js:14841:25)
at format (/home/ubuntu/platform-themes/themes/module-student-template-cme@feature-data-builds/node_modules/prettier/index.js:15063:14)
at formatWithCursor (/home/ubuntu/platform-themes/themes/module-student-template-cme@feature-data-builds/node_modules/prettier/index.js:15080:12)
at /home/ubuntu/platform-themes/themes/module-student-template-cme@feature-data-builds/node_modules/prettier/index.js:54672:12
at Object.format (/home/ubuntu/platform-themes/themes/module-student-template-cme@feature-data-builds/node_modules/prettier/index.js:54692:12)
at t.default.<anonymous> (/home/ubuntu/.vscode-server/extensions/esbenp.prettier-vscode-5.6.0/dist/extension.js:1:59826)
at Generator.next (<anonymous>)
at s (/home/ubuntu/.vscode-server/extensions/esbenp.prettier-vscode-5.6.0/dist/extension.js:1:54110)`
The following valid Hugo snippet
{{ if $load }}
{{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\" async></script>" (printf $v.url $v.version) $v.sri | safeHTML }}
{{ end }}
results in the plugin incorrectly exiting with a SyntaxError:
SyntaxError: Unexpected closing tag "script". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags
Version: 0.0.10
I can provide the full context if needed for reproduction of the issue.
The Hugo snippet runs fine in Hugo and appears to be a valid Go HTML Template.
Possible issue with formatter parsing HTML within Hugo's printf
? Perhaps an issue with how the plugin handles escaped strings?
Hi @NiklasPor, sorry to bother you (again) 😜 😄 .
I think this might be a follow-up to #12.
The following HTML-template
<header id="site-head" {{ with .Params.header_image }}style="background-image: url({{ . }})"{{ end }}></header>
yields
SyntaxError: Unexpected closing tag "BPGT25EPGT". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags (1:77)
[error] > 1 | <header id="site-head" <BPGT25EPGT>style="background-image: url(BPGT26EPGT)"</BPGT25EPGT>></header>
[error] | ^
The HTML-template above should not yield an "Unexpected closing tag"-error 😸 .
For a real-world example, check out https://github.com/janraasch/hugo-scroll/blob/848f6129ec7dac005cbe7b7c2a7e1772e01cf042/layouts/index.html.
You seem like our only hope for creating a go templating formatter so kudo's on taking on the challenge. I've listed out some formatting bugs I see in hopes of making this cleaner! There are a lot more but this is a starting place.
Notes
{{ }}
should be consistent throughout. Example. {{ if}}
should be {{ if }}
or whatever standard you want to use.Un-formatted
{{ define "successAlertIcon" }}
<svg class="h-5 w-5 text-green-400" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
</svg>
{{end}}
Formatted
{{ define "successAlertIcon" }}
<svg class="h-5 w-5 text-green-400" viewBox="0 0 20 20" fill="currentColor">
<path
fill-rule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
clip-rule="evenodd"
/>
</svg>
{{end}}
Un-formatted
{{ if eq . "test1" }}
1
{{ else if eq . "test2" }}
2
{{ else if eq . "test3" }}
3
{{ else if eq . "test4" }}
4
{{ else if eq . "test5" }}
5
{{ else if eq . "test6" }}
6
{{ else if eq . "test7" }}
7
{{ else }}
{{ . }}
{{ end }}
Formatted
{{ if eq . "test1" }}
1 {{ else if eq . "test2" }}
2 {{ else if eq . "test3" }}
3
{{ else if eq . "test4" }}
4 {{ else if eq . "test5" }}
5
{{ else if eq . "test6" }}
6 {{ else if eq . "test7" }}
7 {{ else }}
{{ . }}
{{ end }}
Un-formatted
{{ $color := "blue" }}
{{ if .type }}
{{if eq .type "attention"}}{{ $color = "yellow" }}{{end}}
{{if eq .type "error"}}{{ $color = "red" }}{{end}}
{{if eq .type "success"}}{{ $color = "green" }}{{end}}
{{if eq .type "info"}}{{ $color = "blue" }}{{end}}
{{end}}
Formatted
{{ $color := "blue" }}
{{ if .type }}
{{if eq .type "attention"}}{{ $color = "yellow" }}{{end}}
{{if eq .type "error"}}{{ $color = "red" }}{{end}}
{{if eq .type "success"}}{{ $color = "green" }}{{end}}
{{if eq .type "info"}}{{ $color = "blue" }}{{end}}
{{end}}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.