How to put JavaScript in Laravel make:auth - javascript

Hello everyone so new to laravel here, I just want to ask how to put JS into the file that automatically created when running php artisan ui vue --auth, because whenever I try to add it into resources/views/auth/register.blade.php I get
[Vue warn]: Error compiling template:
Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as , as they will not be parsed.
sorry for random question I just want to know how, and also how to add css, thank you so much in advance
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
You are logged in!
</div>
</div>
</div>
</div>
more code here since they dont allow
#endsection

You're trying to add a <script> to your blade #section, which is why you're getting that error. There are a few ways to do this.
1.. Add your script tags to views/layouts/app.blade.php right before the </body> tag, for example:
<script></script>
</body>
</html>
2.. Place them in your <head> tag and add the defer attribute
<script defer></script>
Your register.blade.php and any other view that extends app.blade.php will now have access to these scripts because it extends the app.blade.php layout.
3.. Use the Blade #stack directive to push your script to a stack. Stacks can be named, in this example lets simply use the name scripts. Add this to register.blade.php
#push('scripts')
<script></script> <!-- Add your JS file or JS code -->
#endpush`
Now in the <head> tag of your app.blade.php you can place #stack('scripts')
Note: Only register.blade.php will load this script, any other view that extends app.blade.php will not have access to it.

Related

Including Javascript codes with #stack not working

I'm working with Laravel 8 and I have a master.blade.php goes like this:
<!DOCTYPE html>
<html>
<head>
<!-- including scripts and stylesheets -->
</head>
<body>
#yield('content')
<script src="/plugins/jquery/jquery.min.js"></script>
#stack('scripts')
</body>
</html>
Then at content.blade.php, I added this as my dynamic content:
#extends('admin.master')
#section('content')
{{ $title }}
...
{{ $slot }}
#endsection
After that I have created some new file and used the components like this:
#component('admin.layouts.content' , ['title' => 'example file'])
#slot('breadcrumb')
<li class="breadcrumb-item active">Example File</li>
#endslot
...
#endcomponent
#push('scripts')
<script>
console.log(1); // to check if the js codes can be run on page
</script>
#endpush
But the problem is that #push('scripts') not working at all! Meaning that this way of including Javascript codes is wrong.
So how can I properly include them in my example page properly?
Note that I don't want to include js codes in content.blade.php because it loads in every single page!
You can try to swap the order of #push and #component
#push('scripts')
<script>
console.log(1); // to check if the js codes can be run on page
</script>
#endpush
#component('admin.layouts.content' , ['title' => 'example file'])
#slot('breadcrumb')
<li class="breadcrumb-item active">Example File</li>
#endslot
...
#endcomponent
I guess it's got something with how blade files are parsed and compiled. So when #component | <x-component> comes before #push, what probably happens is that the component gets rendered by the blade compiler engine and then there's no placeholder for the #push directive to merge contents on the stack.
Faced a similar issue once and learnt that when using components the #push should come before the #component | <x-component> - order is important when using stacks with component.

Run jQuery Functions After AngularJS Loaded Views and Included Partials

I'm using both AngularJS (v1.6.4) and jQuery (v2.1.4) in my web application. I included static html files using ng-include. So my index.html is like that:
<body>
<div id="wrapper" ng-controller="mainCtrl">
<div ng-include="'partials/header.html'"></div>
<div ng-include="'partials/menu.html'"></div>
<div class="content-page">
<div ng-view></div>
<div ng-include="'partials/footer.html'"></div>
</div>
</div>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="plugins/jquery-datatables-editable/jquery.dataTables.js"></script>
<script src="plugins/datatables/dataTables.bootstrap.js"></script>
<script src="assets/js/main.js"></script>
<script>
$("#datatable-editable").DataTable();
</script>
</body>
As you see above I have 3 include files and 1 view. I used datatable in angular view. And I want to initialize it in my index.html file with $("#datatable-editable").DataTable(); But it doesn't work. When I write html elements directly to the page instead of including, it works fine. Why is this happening? How can I solve it?

Where should I include a script for a view component?

I have tried adding a section script inside a view component's view.
#section scripts {
<script src="~/somepath" asp-append-version="true"></script>
}
I also have the Render Section in the shared layout
#RenderSection("scripts", required: false)
When used in partial views and elsewhere in the project the script loads fine. However when in a View Component the script does not load.
I suppose I could include the script in the section tag of every view that calls the component. I feel this does not fit with the self contained nature of a view component.
Is there another way I can do this?
I also had problems with sections tag in viewcomponents. Turns out, to the best of my knowledge, there is no support for it in viewcomponents. See https://github.com/aspnet/Home/issues/2037
Jake Shakesworth has implemented a tag helper as shown in:
Javascript in a View Component
On the other hand you could just include it in your viewcomponent as an
<script defer src"...">
</script>
My requirement was to show a google map from a viewcomponent. Problem was that the script was getting called before the jquery, jquery.ui stuff.
By using defer you are telling the parser not to execute it until the document had loaded thus avoiding the problem of the having to put it in the layout for proper execution.
Defer is supported by chrome, safari, and ie(10+), ff(3.6+), o(15+)
Hope this helps
This is an example of my code:
#using MobileVet.WebApp.Services;
#inject ISettingsService SettingsService
#{
var Options = SettingsService.Value();
<!--Service Area-->
<div class="container-fluid">
<div class="row p-3">
<!--First column-->
<div class="col-md-3">
<h5 class="title">Site Navigation</h5>
<ul>
<li>Home</li>
<li>Services</li>
<li>Link 3</li>
<li>Link 4</li>
</ul>
</div>
<!--/.First column-->
<hr class="w-100 clearfix d-md-none">
<!--Second column-->
<div class="col-md-9">
<div id="map-canvas" style="min-height: 300px; min-width: 200px;">
</div>
</div>
<!--/.Second column-->
</div>
</div>
<!--Service Area-->
<script src="http://maps.google.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXXX&sensor=false"></script>
<script type="text/javascript" src="~/js/components/servicearea.js" defer ></script>
}
Note that you would probably need to write some logic to prevent the script to be included multiple times if the view component is present more than once on a page, which was not my case
From what I have seen, a "#section Scripts {}" in a ViewComponent is ignored and does not render in the relevant #RenderSection() of the ViewComponents _*layout.cshtml
Why that is I do not know.
#section scripts { } in viewcomponents is ignored and not rendered by Asp.Net rendering engine. So just use at the end of the view component. Also if your jquery scripts are specified at the end in your layout, then jquery will not be available in your viewcomponents. Of course moving the jquery script to the head section in layout will solve the problem but it is recommended to load the js files at the end.
So if you want to keep jquery scripts at the end of layout and still use jquery in viewcomponents, you could use javascript domcontentloaded and any jquery can be written inside domcontentloaded. Not a permanent good approach but works for me.
<script>
document.addEventListener('DOMContentLoaded', function (event) {
console.log($ === jQuery)
});
</script>
Or as mentioned by #Alberto L. Bonfiglio you could also try to move your script to another JS file and defer load it in your viewcomponent:
<script src="viewComponentScript.js" defer></script>
This is how I approached inserting scripts into a view component using Asp.net core 2.0.
First I created a partial view which I placed inside of the view components view folder.
Path: Views/Shared/Components/CalendarWidget/_CalendarScriptsPartial.cshtml
_CalendarScriptsPartial.cshtml
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/moment/moment.js"></script>
<script src="~/lib/fullcalendar/dist/fullcalendar.js"></script>
<script src="~/js/calendarWidget.js"></script>
</environment>
<environment exclude="Development">
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/moment/min/moment.min.js"></script>
<script src="~/lib/fullcalendar/dist/fullcalendar.min.js"></script>
<script src="~/js/calendarWidget.js"></script>
</environment>
Then, I brought in the scripts via the Html partial async helper method inside of my view components view.
Path: Views/Shared/Components/CalendarWidget/Default.cshtml
Default.cshtml
<section id="calendar"></section>
#await Html.PartialAsync( "Components/CalendarWidget/_CalendarScriptsPartial" )
And for the sake of completeness here is my view components class.
Path: ViewComponents/CalendarWidgetViewComponent.cs
CalendarWidgetViewComponent.cs
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace LodgersChoice.ViewComponents
{
public class CalendarWidgetViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync( )
{
return View( );
}
}
}
Note: Async isn't currently required in my example but I intend to inject a repository into the ctor of the class which will be using async/await.
Note 2: Once I'm done developing this I plan on bundling and minifying everything down to one script.
I'm registering the ViewComponents scripts in a scoped service, the registered scripts are then rendered after the scripts section in layout.
ViewComponentsService.cs
using System;
using System.Collections.Generic;
namespace YourProject.Services
{
public class ViewComponentsService
{
private readonly List<Func<object>> _scripts = new List<Func<object>>();
public IEnumerable<Func<object>> Scripts {
get {
foreach (var script in _scripts)
{
yield return script;
}
}
}
// A dictionary could be used as type for the _scripts collection.
// Doing so a script Id could be passed to RegisterScript.
// Usefull if only one script per ViewComponent type needs to be rendered.
public void RegisterScript(Func<object> script) {
_scripts.Add(script);
}
}
}
Don't forget to register the service in startup.
services.AddScoped<ViewComponentsService>();
Example ViewComponent
Here we have the ViewComponent and its scripts in the same file!
#model UI.FailUserFeedback
#inject Services.ViewComponentsService _viewComponentsService
#{
var modalId = UI.Utilities.RandomId();
var labelId = UI.Utilities.RandomId();
}
<div class="modal fade" id="#modalId" tabindex="-1" aria-labelledby="#labelId" aria-hidden="true">
#*omitted for brevity*#
</div>
#{
// the script is written here
Func<dynamic, object> RenderScript =
#<script>
(function () {
var modal = new bootstrap.Modal(document.getElementById('#modalId'));
modal.show();
})();
</script>;
// and registered here
_viewComponentsService.RegisterScript(() => RenderScript(this));
}
Layout
#inject Services.ViewComponentsService _viewComponentsService
...
#await RenderSectionAsync("Scripts", required: false)
#foreach(var script in _viewComponentsService.Scripts) {
#script();
}
In case of ViewComponent called by Controller inside a modal or another element being rendered after page is fully loaded, defer won't work either. Instead you must put these scripts in a parent View or in _Layout.
In my case it was an ajax form and
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script src="~/lib/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.js"></script>
or even#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
would not be loaded and caused problems posting the form correctly.
View component in ASP.NET Core acts like independent view with separated controller, so you can insert bellow tag above of your view component
#{
Layout = null;
}
after that insert bellow tag to use related script,for example:
<environment include="Development">
<script src="~/js/chart.js"></script>
</environment>
<environment exclude="Development">
<script src="~/js/chart.min.js"></script>
</environment>

How do get JQuery to work when I am using AngularJS partials?

I have the below code. However, my JQuery wont run when the #id and .classes it is looking for are in partials when viewing this static page. How do I get it to work?
<body ng-app>
<h2>JQuery wont run if code it is looking for is in a Partial</h2>
<div ng-include="'_includes/partials/menu.html'" ></div>
<br />
<h2>JQuery will work if the code it is looking for is here on the page (DOM)</h2>
<div class="container">
<div class="row">
<div class="col-xs-12">
<ul class="nav">
<li><a>Home</a></li>
<li><a>About</a></li>
<li><a>Services</a></li>
</ul>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="_includes/scripts/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="_includes/scripts/custom.js"></script>
</body>
It is not a good practice to try to find html elements and modify them in an AngularJS app as you would normally do in a JQuery enabled html. Instead, try to implement whatever you are thinking of only using Angular.
Anyway you want to use ng-directives instead jQuery calls.

JavaScript: print working directory, list files in subdirectory to console

I'm new to JavaScript, and am working on a website where you can upload files and display a result summary.
I've successfully uploaded the results to the webpage / on the server.
However, I am having trouble reading in an uploaded HTML file from the server ,to load the HTML file and display it.
Below is the HTML script which prints the path to the HTML file. but how to load the HTML i.e. run the HTML file using javascript??
<!doctype html>
<html>
<head>
<title>Summary Report</title>
<link rel="stylesheet" type="text/css" href="https://da1s119xsxmu0.cloudfront.net/libraries/basestrap/1.0.0/css/master.min.css" />
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="col-xs-12">
<h3>Summary Report</h3>
<h4>App Results:</h4>
<ul>
<h3>{{ result.name }}</h3>
<h4>Result Files:</h4>
<ul>
{% for key in result.files %}
{% if key contains '.html' %}
<li>{{ key }}</li>
</ul>
</div>
</div>
</div>
</body>
</html>
Output
The output is an unordered list of the html file on the server that I need to be read into the screen console.
1662b5e25a574e89abf2a5490005585a/expressionCSV/limmaWithMeta.html
What is your backend running? node.js? HTML/client side JavaScript isn't going to help you list the files uploaded to the server. You should include the code that populates session.results.
In general, based on what you've mentioned about the current behavior, I'd suggest that you use a recursive function to traverse the subdirectories:
function listTree(root) {
print(root);
if (root.isDirectory()) {
root.getFiles().forEach(function(file) {
listTree(file);
});
}
}
As mentioned above, this would go in the server side code since that's where the files are actually stored. (Your users' computers shouldn't be able to access all the files on the server, right? :) )

Categories

Resources