golang renderer.HTML not picking javascript file from inside the template - go

Trying to publish a login page using "github.com/thedevsaddam/renderer" package renderer . Not able to call the .js file from inside the template. When tried inlining javascript it worked fine, but not able to load the .js file.
my file structure is
Project
|
+-main.go
|
+-handlers
| |
| +- routes.go
| |
| +- login.go
+-views
| |
| +- _login.html
| +- login.js
main.go
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/higuestssg/handlers"
)
func main() {
router := mux.NewRouter().StrictSlash(true)
// This will serve files under http://localhost:8000/static/<filename>
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("views/"))))
portalRouter := router.PathPrefix("/portal").Subrouter()
handlers.HandleRoutes(portalRouter)
fmt.Println("listening at localhost:10001")
log.Fatal(http.ListenAndServe(":10001", router))
}
routes.go
package handlers
import (
//"net/http"
"github.com/gorilla/mux"
)
func HandleRoutes(r *mux.Router){
r.HandleFunc("/login", loginHandler)
r.HandleFunc("/healthTest", healthTestHandler)
}
login.go
package handlers
import (
"fmt"
"net/http"
//"github.com/gorilla/mux"
"github.com/thedevsaddam/renderer"
)
var rnd *renderer.Render
func init() {
opts := renderer.Options{
ParseGlobPattern: "./views/*.html",
}
rnd = renderer.New(opts)
}
// loginHandler renders login page
func loginHandler(w http.ResponseWriter, r *http.Request) {
data := struct {
Val1 string
Val2 string
}{
"test100",
"test2",
}
fmt.Println("login page hit")
rnd.HTML(w, http.StatusOK, "_login", data)
}
_login.html
{{ define "_login" }}
<!--
https://medium.com/#thedevsaddam/easy-way-to-render-html-in-go-34575f858026
-->
<!DOCTYPE html>
<html lang="en">
<!-- Bootstrap import CSS-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<body>
<div class="container">
<div class="starter-template jumbotron text-center">
<h1>HI GUEST</h1>
<div class="col-sm-4">
<p class="lead">Welcome to <strong>HI_GUEST --ssg</strong> page</p>
</div>
</div>
</div><!-- /.container -->
<div class="row">
<div class="col-sm-4"><p class="lead" id="idtest1">Test1</p></div>
<div class="col-sm-4"><p class="lead">Test2</p></div>
<div class="col-sm-4"><p class="lead"><button type="button" class="btn btn-info btn-lg" name="btn_ip" id="btn_id" onclick="myFunction()">{{.Val1}}</button></p></div>
</div>
</body>
<script type='text/javascript' src='login.js'></script>
</html>
{{ end }}
login.js
function myFunction()
{
alert("Hello");
}
$(document).ready(function () {
alert("Hello");
});
When checked in chrome using viewSource, when clicked on login.js its showing 404 not found

updated _login.html , its working fine with #mkopriva suggestion
{{ define "_login" }}
<!--
https://medium.com/#thedevsaddam/easy-way-to-render-html-in-go-34575f858026
-->
<!DOCTYPE html>
<html lang="en">
<!-- Bootstrap import CSS-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<body>
<div class="container">
<div class="starter-template jumbotron text-center">
<h1>HI GUEST</h1>
<div class="col-sm-4">
<p class="lead">Welcome to <strong>HI_GUEST --ssg</strong> page</p>
</div>
</div>
</div><!-- /.container -->
<div class="row">
<div class="col-sm-4"><p class="lead" id="idtest1">Test1</p></div>
<div class="col-sm-4"><p class="lead">Test2</p></div>
<div class="col-sm-4"><p class="lead"><button type="button" class="btn btn-info btn-lg" name="btn_ip" id="btn_id" onclick="myFunction()">{{.Val1}}</button></p></div>
</div>
</body>
<script type='text/javascript' src='/static/login.js'></script>
</html>
{{ end }}

Related

why wire:click not working in laravel livewire

laaravel version:8.0
livewire version: 2.x
Hi there
I am new to laravel livewire and facing a strange issue!. in order to execute the action i used wire:click as can be seen in the following code in my admin-login.blade.php
#section('content')
<div class="admin-login display-flex flex-align-items-center flex-justify-content-center">
<button wire:click="toDo">{{$login}}</button>
<div class="admin-form display-flex flex-direction-column flex-justify-content-center" >
#livewire('header',['name'=> 'Admin Login','width'=> '100%','height' => '20%'])
<form class=" display-flex flex-direction-column flex-justify-content-center" >
<section style="margin: 2%;">
<label for="Email">Email :<span style="color: red">*</span></label>
<input type="email" required>
</section>
<section style="margin: 2%;">
<label for="Password">Password :<span style="color: red">*</span></label>
<input type="password" required>
</section>
<button style="width: 40%; height: 5vh; align-self: center;justify-self: flex-end;">Login</button>
</form>
</div>
</div>
#endsection
my app.blade.php file in layouts directory is
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="{{asset('css/admin/app.css')}}">
#livewireStyles
<title>Admin Dashboard</title>
</head>
<body>
#livewire('nav-bar')
#livewire('side-bar')
#yield('content')
</body>
#livewireScripts
<script>
var isStudentDropDown = false
Livewire.on('showSidebar',()=>{
document.getElementById('sidebar').style.display = "block"
})
Livewire.on('closeSidebar',()=> {
document.getElementById('sidebar').style.display = "none"
})
Livewire.on('showDropdown',data => {
if(document.getElementById(data).style.display === "block"){
document.getElementById(data).style.display = "none"
}else{
document.getElementById(data).style.display = "block"
}
})
</script>
</html>
now my component php file
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class AdminLogin extends Component
{
public $login = "login";
public function render()
{
return view('livewire.admin-login');
}
public function hell(){
$this->login = "signup";
}
public function toDo(){
dd('do some thing');
}
}
i have checked my devtools and got no request being send to the server
Pardon me for any mistake!
Extends layouts from component
ref link https://laravel-livewire.com/docs/2.x/rendering-components#custom-layout
public function render()
{
return view('livewire.admin-login')
->extends('layouts.app')
->section('content');
}
and remove #section from admin-login.blade.php

How to render/show images in HTML created on the fly with Golang and gin-gonic

I'am generating QR codes and right after I need to show them in an HTML without saving them as images.
So far I can generate them but I have problems rendering them in the HTML
I have here the golang code that generates the QR and the HTML template that try to render them
golang
import (
"fmt"
"github.com/gin-gonic/gin"
qrcode "github.com/skip2/go-qrcode"
)
func renderQRExport(c *gin.Context){
var images [][]byte
var img []byte
var err error
for i := 0; i < 25; i++ {
img, err = qrcode.Encode("https://example.org", qrcode.Medium, 256)
images = append(images, img)
if err != nil {
fmt.Print(err)
}
}
render(c, gin.H{
"images": images,
}, "qr.html")
}
HTML Template
<!doctype html>
<html class="no-js" lang="">
<head>
<title>QR export</title>
{{template "imports.html"}}
</head>
<body>
<div class="margin-body-log-in-worker">
<div class="row">
{{range .images}}
<div class="col-4 col-sm-4 col-md-3 col-xl-2 center">
<img src="data:image/png;base64,{{.image}}" class="img-fluid image-dashboard" />
</div>
{{end}}
</div>
</div>
</body>
</html>
One of the things that I'am not able to do, as they say in this article:
https://www.sanarias.com/blog/1214PlayingwithimagesinHTTPresponseingolang
and also the Encode method itself says "To serve over HTTP, remember to send a Content-Type: image/png header."
How can I set properly the content type in the request using gingonic and how to decode properly in the HTML?
I solved my own question thanks to this article: https://www.socketloop.com/tutorials/golang-encode-image-to-base64-example
The proble is that i needed to Encode it to String with 'imgBase64Str := base64.StdEncoding.EncodeToString(buf)'
So the final code to work is as follows:
Golang
func renderQRExport(c *gin.Context){
var images []string
var img []byte
var err error
for i := 0; i < 25; i++ {
img, err = qrcode.Encode("https://example.org", qrcode.Medium, 256)
img2 := base64.StdEncoding.EncodeToString(img)
images = append(images, img2)
if err != nil {
fmt.Print(err)
}
}
render(c, gin.H{
"images": images,
}, "qr.html")
}
HTML
<!doctype html>
<html class="no-js" lang="">
<head>
<title>QR export</title>
{{template "imports.html"}}
</head>
<body>
<div class="margin-body-log-in-worker">
<div class="row">
{{range .images}}
<div class="col-4 col-sm-4 col-md-3 col-xl-2 center">
<img src="data:image/png;base64,{{.}}" class="img-fluid image-dashboard" />
</div>
{{end}}
</div>
</div>
</body>
</html>

How to use Link in NavItem in ReactJS without using node / import

I'm developing a multi page application in Spring and ReactJS without using NodeJS.
index.html:
<body>
<div class='container'>
<div id='root'>test</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js"></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-bootstrap/0.31.5/react-bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router-bootstrap/0.24.4/ReactRouterBootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router-dom/4.2.2/react-router-dom.min.js"></script>
<script type="text/babel" src="/public/navigation.js"></script>
<script type="text/babel" src="/public/test.js"></script>
</body>
test.js:
ReactDOM.render(<div><TestNavigation /></div>, document.getElementById('root') );
navigation.js
var Navbar = ReactBootstrap.Navbar,
Nav = ReactBootstrap.Nav,
NavItem = ReactBootstrap.NavItem;
var LinkContainer = ReactRouterBootstrap.LinkContainer;
class TestNavigation extends React.Component {
navItemHandleClick() {
console.log("NavItem Clicked")
}
render() {
return (
<div className="col-md-12">
<Navbar id="navbar"collapseOnSelect>
<Navbar.Collapse>
<Nav >
<NavItem eventKey={1} href="#" >Page 1</NavItem>
<NavItem eventKey={2} href="#" className="navLink" onClick={this.navItemHandleClick}>Page 2</NavItem>
<NavItem eventKey={3} href="#" className="navLink" >Page 3</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
</div>
);
}
}
I'm not able to have link inside NavItem. I don't want to use nodejs, so import statement in js file will not work. Please help. Thanks.
You can use <Navbar.Link> to get nav-link inside your NavItem like below
<NavItem eventKey={1} href="#">
<Navbar.Link>Page 1</Navbar.Link>
</NavItem>
The below code worked. Thanks
<NavItem eventKey={1} ><Link className="navLink" to="/" id="navcolor">Home</Link></NavItem>

Golang template does not render html

I created a subfolder called 'views' in my web root directory. Within the View folder, I have the static folder which contains the css and js files.
The html pages are rendered when I have the html files in the web root. However they do not render when placed within the views folder. I am using template.ParseGlob to parse the file and ExecuteTemplate to render.
package main
import (
"html/template"
"net/http"
"github.com/gorilla/mux"
)
var router = mux.NewRouter()
var tmpl *template.Template
func init() {
tmpl = template.Must(template.ParseGlob("view/*.html"))
}
func indexPage(w http.ResponseWriter, r *http.Request) {
err := tmpl.ExecuteTemplate(w, "signin", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func main() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
router.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("view/"))))
router.HandleFunc("/", indexPage)
http.ListenAndServe(":8091", router)
}
HTML files: Have defined the header and footer in index.html which I refernce in the signin.html file
{{ define "header"}}
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>User Sign in</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="/static/css/main.css">
<script src="/static/js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>
</head>
<body>
{{end}}
{{define "footer"}}
<footer class="panel-footer"><p>© Company 2016</p></footer>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script>
<script src="/static/js/vendor/bootstrap.min.js"></script>
<script src="/static/js/main.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X','auto');ga('send','pageview');
</script>
</body>
</html>
{{end}}
signin.html file:
{{define "signin"}}
{{template "header" .}}
<h1 class="alert alert-info">Login</h1>
<div class="container">
{{with .Errors.message}}
<div class="alert alert-danger">
{{.}}
</div>
{{end}}
<form method="POST" action="/">
<label class="form-control" for="uname">User Name</label>
<input class="form-control" type="text" id="uname" name="uname">
<label class="form-control" for="password">Password</label>
<input class="form-control" type="password" id="password" name="password">
<button class="btn btn-info" type="submit">Submit</button>
</form>
{{template "footer" .}}
{{end}}
Why is it that this doesn't work when I place the html files in the sub-directory 'views'. The only thing that changes is the argument to parseGlob.
I believe all you need to do is remove this line:
router.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("view/"))))
Works for me. Though you need to clean up your html a bit too - I see at least a missing </div>.
Templates are processed on the server and do not need to be served over internet. At the same time this route entry conflicts with the following one (indexPage) which defines another handler for the same route entry ("/"). So when you open it in a browser, server just send template files over internet. While indexPage handler is never called as directory handler is matched first.
Also you talking about "views" folder, but you code says "view" (without 's' at the end). Could be another simple reason.

UI Bootstrap and Laravel Blade Templating

I am using UI Bootstrap in my project : UI Bootstrap
Problem : I cannot handle javascript <script> tags with blade templating. Getting internal server error (500)
Here's my Views path :
Views
includes
layouts
pages
Here's my includes/head.blade.php file :
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="">
<meta name="author" content="Scotch">
<title>Title</title>
{{ HTML::style('../public/css/bootstrap.min.css') }}
{{ HTML::script('//public/js/jquery-1.11.1.js')}}
Here's my layouts/home.blade.php file :
<!doctype html>
<html ng-app="ui.bootstrap.demo">
<head>
#include('includes.head')
{{ HTML::script('//public/js/ui.bootstrap.min.js') }}
{{ HTML::script('//public/js/angular.min.js')}}
{{ HTML::script('//public/js/example.js')}}
</head>
<body>
<div class="container">
<header class="row">
#include('includes.header')
</header>
<div id="main" class="row">
#yield('content')
</div>
<footer class="row">
#include('includes.footer')
</footer>
</div>
</body>
</html>
Here's my pages/home.blade.php file :
#extends('layouts.home')
#section('content')
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
<a ng-click="selected.item = item">{{ item }}</a>
</li>
</ul>
Selected: <b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
<button class="btn btn-default" ng-click="open()">Open me!</button>
<button class="btn btn-default" ng-click="open('lg')">Large modal</button>
<button class="btn btn-default" ng-click="open('sm')">Small modal</button>
<div ng-show="selected">Selection from a modal: {{ selected }}</div>
</div>
#stop
Here's my public/js/example.js file :
angular.module('ui.bootstrap.demo', ['ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $modal, $log) {
$scope.items = ['item1', 'item2', 'item3'];
$scope.open = function (size) {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
Here's my ui.bootstrap.min.js injection :
Now here's the problem :
I think in pages/home.blade.php file, i am having problem codes between <script></script> tags.
Check this out :
And here's the error i get (Sorry, the default language is Turkish)
As like i said, my purpose is using both UI Bootstrap and laravel blade templating.
Thanks in advance !
It's a little unclear if this is your only issue, but both Angular and Blade templates use the same tokens for denoting the begin / end of interpolated areas, i.e. {{ and }}. If you want to use them together, you will need to change one of them to something else, otherwise your angular code will be interpreted by Blade on the server and cause a 500 server error.
In Blade this looks like:
Blade::setContentTags('<%', '%>');
Blade::setEscapedContentTags('<%%', '%%>');
In Angular, it would look like this:
var myApp = angular.module('myApp', [], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});

Resources