Is it the optimized way of mixing laravel blade and vuejs - javascript

I am currently make the app.blade.php as
<!DOCTYPE html>
<html>
<head>
<title> abc</title>
<link rel="stylesheet" href='{{URL::asset('/css/style.css ')}}' />
<link rel="stylesheet" href='{{URL::asset('/css/app.css ')}}' />
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
</head>
<body>
<div class="wrapper" id="app" v-cloak>
#yield('content')
</div>
<script src="{{ URL::asset('js/app.js') }}"></script>
<script>
var vm = new Vue({
el: '#app',
#yield('vue')
});
</script>
</body>
</html>
And subsequent pages like dashboard.blade.php as
#extends('layouts.app')
#section('title', 'customer :')
#section('content')
<titlebar></titlebar>
<dashboard-page
:data=data
:options=options
#update=updatethedata
><dashboard-page>
#endsection
#section('vue')
data:{
data:{...},
options={...},
},
methods:{
updatethdata:function(){
...;
}
},
#endsection
It works as intended. but i don't know this is how it should be merged or there as some better ways to do it .
It gives me access to both blade and vue to customize my application . but it makes the code much difficult as the js is in blade file which doesnot get minified. more over none syntax highlighter works , as it is not in a script tag.

Related

Why emitted events of livewire is not triggered?

In laravel 7 learning livewire/livewire 1.3 I encountered that emitted
events are not always triggered
I created component with command
php artisan make:livewire hostel/hostelsHomepageSpotlight
and simplifying the code I do not see alert of event.
In app/Http/Livewire/Hostel/HostelsHomepageSpotlight.php :
<?php
namespace App\Http\Livewire\Hostel;
use Auth;
use DB;
use App\Config;
use App\Hostel;
use App\HostelImage;
use App\library\CheckValueType;
use App\Settings;
use Livewire\Component;
class HostelsHomepageSpotlight extends Component
{
public function render()
{
$hostels = [];
$current_page= 1;
$hostel_rows_count = Hostel
::getByStatus('A')
->count();
$this->emit('hostelsHomepageSpotlightOpened', [ 'mode'=> 'hostels_homepage_spotlight', 'current_page'=>$current_page, 'hostel_rows_count'=>$hostel_rows_count ] ); // EMIT EVENT
return view('livewire.hostel.hostels-homepage-spotlight', [
'hostelsDataRows' => $hostels,
'hostel_rows_count'=> $hostel_rows_count,
'current_page'=> $current_page,
]);
}
}
and in resources/views/livewire/hostel/hostels-homepage-spotlight.blade.php:
<div>
<h1>hostelsHomepageSpotlightOpened</h1>
</div>
<script>
// If to uncomment line below I see alert
// alert( 'resources/views/livewire/hostel/hostels-homepage-spotlight.blade.php::' )
window.livewire.on('hostelsHomepageSpotlightOpened', data => {
// I DO NOT SEE ALERT BELOW ANYWAY
alert( 'hostelsHomepageSpotlightOpened::' )
console.log('facility_opened data::')
console.log(data)
// alertsInit(data.mode)
// lazyImagesInit("img.lazy_image")
})
</script>
Why event is not triggered ? Is there is a way to debug it ?
UPDATED # 2:
I know the rule about wrapping div(without any class or styles definitions).
Have I also to remove JS code ?
I tried to move all JS code in resources/js/app.js :
window.$ = window.jQuery = require('jquery');
require('./bootstrap');
var Turbolinks = require("turbolinks")
Turbolinks.start()
// If to uncomment the line below I see it
// alert( '::resources/js/app.js' )
window.livewire.on('hostelsHomepageSpotlightOpened', data => {
// I do not see this alert
alert( 'hostelsHomepageSpotlightOpened::' )
console.log('facility_opened data::')
console.log(data)
// alertsInit(data.mode)
// lazyImagesInit("img.lazy_image")
})
and in my resources/views/layouts/app.blade.php :
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" xmlns:livewire="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel:Livewire</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet" type="text/css">
<link rel="icon" type="image/png" href="/favicon.ico"/>
<link href="/css/app.css" rel="stylesheet">
<script src="{{ asset('js/lazyload.js') }}"></script>
<!-- Styles -->
#livewireStyles
#livewireScripts
<script src="{{ asset('/js/app.js') }}"></script>
<script src="{{ asset('/js/app/app_funcs.js') }}"></script>
</head>
<body class="text-center">
<div class="flexbox-parent page_container " id="page_content">
<header class="flexbox-item header">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
...
</nav>
</header>
<main class="flexbox-item fill-area content flexbox-item-grow">
#yield('content')
</main>
<footer class="flexbox-item footer ml-3 mr-3">
...
<p class="m-2">copyright_text</p>
</footer>
</div>
</body>
</html>
And my code is nit triggered anywat!
I suppose that is valid structure of my app as app.js AFTER #livewireStyles
and #livewireScripts
UPDATED # 3:
I tried and that does not work. I have login form :
<article class="page_content_container">
...
<form class="form-login" wire:submit.prevent="submit">
<input
wire:model.lazy="form.email"
name="email"
id="email"
class="form-control editable_field"
placeholder="Your email address"
autocomplete=off
>
</form>
...
</article> <!-- page_content_container -->
{{--#push('scripts')--}}
<script>
$("#email").focus();
</script>
{{--#endpush--}}
When #push/#endpush are commented as on lines above it works ok and focus is set to email input.
But if to uncomment these 2 lines focus is not set.
I modified my resources/views/layouts/app.blade.php :
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel:Livewire</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet" type="text/css">
<link rel="icon" type="image/png" href="/favicon.ico"/>
<link href="/css/app.css" rel="stylesheet">
<!-- Styles -->
#livewireStyles
<script src="{{ asset('/js/app.js') }}"></script>
<script src="{{ asset('js/lazyload.js') }}"></script>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine#v2.x.x/dist/alpine.min.js" defer></script>
#livewireScripts
#stack('scripts')
<script src="{{ asset('/js/app/app_funcs.js') }}"></script>
app.js - is first as bootstrap and jquery are included there...
Thanks!
Livewire expects components wrapped by a div element.
Sample:
< div>
Your content...
</ div>
What I am saying is that I am not sure you can include javascript in your Livewire blade. Try by moving it out to your app.js file and see if it works because the rest looks good.
I remember having trouble just because the blade’s first line was a html comment, instead of 🙈
So, always, first line of your livewire blade must be < div>, and last line </ div>
Hope that helps!
If you want to write script under livewire blade try this way. in your master layout put under #livewireScripts
#stack('scripts')
Now you can push scripts in this stack from your livewire blade file like this:
#push('scripts')
<script>
// some js code
</script>
#endpush
UPDATED: It makes sense why in your case it does NOT work. You should NOT emit the event in the RENDER function IFF you want to listen for it in the same view that is about to be rendered. In simple words for your case, the emit happens before the view loads, thus, by the moment your view is ready, it will be a 'bit' late to listen to it, you lost it! :-)
Solution: put the JS (the window.livewire.on... ) one step outside so it will be already ready by the moment you emit the event in the render.
In simple words, place the JS code in the scripts section of the parent file, the file you include the following
#livewire('hostel.hostels-homepage-spotlight')
P.S. When you are dealing with livewire, to listen for an event or fire one,
do not forget to wrap it in the document ready, i.e.,
$( document ).ready(function() {
livewire.emit('event_foo', 'foooo');
});
Thus, your spotlight PARENT page should look something like this:
<script>
$( document ).ready(function() {
window.livewire.on('hostelsHomepageSpotlightOpened', data => {
alert( 'hostelsHomepageSpotlightOpened::' )
console.log('facility_opened data::')
console.log(data)
});
});
</script>
Cheers,

Scripts loaded in default template not working in views in laravel 5

Why is my js not working as it should in edit.blade.php view. My views are structured as follows:
Filename: profile_main.blade.php
#extends('layouts.main')
#section('head')
#yield('style')
#stop
<!-- Available at the footer of page before body tag closes -->
#section('scripts')
<script src="{{ URL::asset('js/jquery-ui-1.11.4.custom/jquery-ui.js') }}"></script>
<script src="{{ URL::asset('js/search.js') }}"></script>
<script src="{{ URL::asset('js/application.js') }}"></script>
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>
#stop
Filename: training_main.blade.php
#extends('layouts.profile_main')
#section('style')
<link href="{{ URL::asset('css/application/index.css') }}" rel="stylesheet">
#stop
#section('body')
<div id="content-header">
<img alt="user_icon" src="{{ asset('images/general/admission_page_logo.jpg') }}" class="img-responsive"/>
<h1>#yield('page_heading')</h1>
<h3>#yield('page_desc')</h3>
</div>
<hr class="header_underline"/>
#yield('training_body')
#stop
Filename: edit.blade.php
#extends('trainings.training_main')
#section('page_heading')
Edit Training Details
#stop
#section('page_desc')
General
#stop
#section('training_body')
#stop
I have some jquery functions in application.js. I notice that these functions are not working in edit.blade.php. For example
Filename: application.js
$("document").ready(function() { alert('Great') });
It does not alert when the edit.blade.php view is loaded. But when I look at the page source, everything seems to be loaded fine like so:
<!-- Javascript -->
<script src="http://localhost:8000/js/jquery-1.11.3.js"></script>
<script src="http://localhost:8000/js/bootstrap.min.js"></script>
<script src="http://localhost:8000/js/main.js"></script>
<script src="http://localhost:8000/js/jquery-ui-1.11.4.custom/jquery-ui.js"></script>
<script src="http://localhost:8000/js/search.js"></script>
<script src="http://localhost:8000/js/application.js"></script>
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>
</body>
What could be the problem here? What are my missing?
The problem was with my js. My js look like so:
$("document").ready(function() {
limitCharacters();
$("#edit_academic_form").on('submit', updateAcademic);
$("#edit_training_form").on('submit', updateTraining);
}
The function limitCharacters() had some syntax errors thus preventing the codes beneath it from ever getting called. I resolved issues with the function and now everything is working fine.
check with php artisan route:list on your terminal,
in 'edit' URI, will showed :
home/{home}/edit
its reason why your js not run, to solve the problem you can rewrite js path in your edit.blade.php.
Or if you have other solution please tell me. Thanks

Node/Express project using EJS partials and angular: Uncaught ReferenceError: angular is not defined

I feel like I have completely missed something here but I am trying to use ejs partials in a single page angular app. I keep getting a Uncaught ReferenceError: angular is not defined in my partial. I think this may have something to do with using ejs partials instead of using ng-include, however I have not had any luck in playing with that. Any help would be amazing.
app.js
(function(){
var app = angular.module('dashboard', []);
app.controller('ItemController', function(){
this.item = items;
});
//need to loop through items in DB for now using these test objects
var items = [
{
name : 'name1',//query to db for name goes here
stock : '4',//query to db
img : '/images/bb-logo.png'//query to db
},
{
name : 'name2',//query to db for name goes here
stock : '6',//query to db
img : '/images/bb-logo.png'//query to db
}
];
})();
index.ejs
<!DOCTYPE html>
<html lang="en" ng-app="dashboard">
<head>
<meta charset="UTF-8">
<title><%= title %></title>
<link rel="stylesheet" href='/libs/font-awesome/css/font-awesome.css'>
<link rel="stylesheet" href='/libs/foundation/css/foundation.css'>
<link rel="stylesheet" href='/stylesheets/style.css'>
<!-- include angular here -->
<script type="text/javascript" href='/libs/angular/angular.js'></script>
<script type="text/javascript" href='/libs/modernizer/modernizer.js'></script>
<script type="text/javascript" src="/angularApp.js"></script>
</head>
<body>
<% include partials/topbar %>
<div class="row">
<div class="large-6 columns etsy-container">
<% include partials/etsy-container %>
</div>
<div class="large-6 columns">
<% include partials/amazon-container %>
</div>
</div>
</body>
</html>
/amazong-container
<div class='store-container'>
<h1 class="left">Amazon</h1>
<span class="store-utility-icons"><i class="fa fa-refresh right"></i><i class="fa fa-times-circle-o right"></i></span>
<div class="clear"></div>
<% include /item %>
</div>
/item.ejs
<div ng-controller="ItemController as store" >
<div ng-repeat="item in store.items">
<img ng-src="{{item.img}}" />
<p>{{item.name}} <i> Stock level: {{item.stock}}</i></p>
</div>
</div>
The way you include Angular is wrong. You have
<script type="text/javascript" href='/libs/angular/angular.js'></script>
but it should be:
<script type="text/javascript" src="/libs/angular/angular.js"></script>
So you have to use src instead of href. Looks like a typical copy/paste error. So, in the end, this has nothing to do with EJS or using partials, it's just wrong HTML ;-).
PS: Apart from that, you're using single quotes for attributes in HTML. Go with double quotes all the times, as this is the usual and common way to do it.
PPS: The same applies to the line where you try to load Modernizr.

How to access to a javascript variable inside another html.twig file in symfony2?

I would like to know how to access to a javascript variable inside another html.twig file in symfony2. Let's assume that we have two html\twig files: file1.html.twig and file2.html.twig, their codes are as below:
The code of file1.html.twig:
<html>
<head>
<script>
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
//here is some code
});
});
</script>
</head>
<body>
</body>
</html>
The code of file2.html.twig:
<html>
<head>
<script>
function f1(){
//here is the code that I need to access to the variable calendar of the file file1.html.twig
}
</script>
</head>
<body>
<form id="EventForm" action='{{path('ikproj_groupe_homepaeventsAdd',{id:idg})}}' method="POST" {{ form_enctype(form) }} onsubmit="f1();">
//here the body of the form
</form>
</body>
</html>
Actually, what I would like to know is how to access to the variable "calendar" of file1.html.twig inside the file file2.html.twig. So my question is it possible to do that??..If yes, how?
Put the code you want to share in a .js file:
// src/Acme/FooBundle/Resources/public/js/sharedCode.js
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
//here is some code
});
});
Then just include the script everywhere you want:
<html>
<head>
...
</head>
<body>
...
{% javascripts '#AcmeFooBundle/Resources/public/js/sharedCode.js' %}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
</body>
</html>

Ember.js: Having problems creating a controller subclass

I am trying to create a custom controller in Ember.js, and am having some trouble trying to make this work. Here is my app.js code:
App = Ember.Application.create();
App.LoginController = Ember.Controller.extend({
actions: {
alert: function() {
alert('yo');
}
}
});
App.LoginManagerView = Ember.View.extend({
templateName: 'login/manager',
})
App.LoginManagerController = Ember.Controller.extend({
needs: ['loginController'],
})
App.Router.map(function() {
this.route("root", {path: "/"});
this.resource("login", function() {
this.route("user");
this.route("manager");
})
});
And here is my html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ember Starter Kit</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/x-handlebars">
<div class="navbar">
<div class="navbar-inner">
{{#link-to 'root'}}Home{{/link-to}}
{{#link-to 'login.user'}}User{{/link-to}}
{{#link-to 'login.manager'}}Manager{{/link-to}}
</div>
</div>
{{outlet}}
</script>
<script type="text/x-handlebars" id="root">
<h1>Home</h1>
</script>
<script type="text/x-handlebars" id="login/user">
<h1>User</h1>
</script>
<script type="text/x-handlebars" id="login/manager">
<h1>Manager</h1>
<p>
Name: {{controller}}
</p>
<button {{action controllers.loginController.alert}}>Alert</button>
</script>
<script src="js/libs/jquery-1.10.2.js"></script>
<script src="js/libs/handlebars-1.1.2.js"></script>
<script src="js/libs/ember-1.4.0.js"></script>
<script src="js/app.js"></script>
</body>
When I click User I can see the user view, but when I click manager I cant see the manager view. In fact, it seems its not even creating the Manager route. If I remove these lines:
App.LoginManagerController = Ember.Controller.extend({
needs: ['loginController'],
})
it works, but I lose access to the login controller instance.
EDIT:
When I look at the Ember console and I cant see the routes, if I go back to js console I get this message:
needs [ controller:loginController ] but it could not be found
How can I make it find the loginController instance?

Categories

Resources