Returning javascript view in Laravel - php

In Ruby on Rails In my controller I can do something like this:
def jstest
respond_to do |format|
format.js
end
end
This would return jstest.js.erb from the relevant views directory
jstest.js.erb
alert("Hello World")
The result being I get hello world alert.
I want to do the same thing in Laravel
In my controller I have:
public function jstest( )
{
return view('jstest');
}
in my view (which I have tried with both jstest.blade.js and just jstest.js)
but I get the error, view cannot be found.
The only way I get this to work is by calling the view jstest.blade.php and including my js in a <script> tag within this php file. but this feels a bit wrong...?
Is this even possible in Laravel? If so, where am I going wrong?
Example use case:
Imagine the following example, I have a table of comments, a user can click a delete button which will send an ajax request to delete the comment.
My Route:
Route::delete('post/comments/{comment}','commentsController#delete');
In my controller:
Public Function delete($comment)
{
$comment->delete();
return commentDeleted.js
}
commentDeleted.js:
$(#comment).remove();
So from the users perspective, they click delete and the comment disappears from their screen without loading a new page.

I don't know if Laravel supports this out of the box, but this is my take on your issue.
This is how I understood your problem: you want to specify a path to .js file as an argument to a function and you want this .js file to be immediately executed when loaded via browser.
I'd do it in these 2 steps
Create a jsview() function that accepts a path, similar to view()
Create the base .blade.php file which will be used by the above
The .blade.php contents
Assumption is that this view will be named javascript.blade.php and it's in resources/views/ directory.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="{{$path}}"></script>
</head>
<body></body>
</html>
The function
function jsview($path)
{
return view('javascript', ['path' => $path]);
}
Usage
<?php
Route::get('/test', function()
{
return jsview('/assets/my.js');
});
This answer isn't really fully complete because your browser will be loading files from public/ directory so all .js files you specify this way would be read from there. I believe Laravel does have something related to resources, but I'm not expert enough on that matter.
This is posted only to outline how to achieve something that you need, but isn't available out of the box.

Related

How to render template through route without any frameworks

I am creating a basic routing system for a bespoke CMS and I am wanting to do this completely in raw PHP without frameworks. So far, I have the routing down, with GET and POST methods working correctly.
Here is my index.php file
<?php
include_once 'Request.php';
include_once 'Router.php';
$router = new Router(new Request);
$router->get('/', function() {
return <<<HTML
<h1>Hello world</h1>
HTML;
});
$router->get('/profile', function($request) {
return <<<HTML
<h1>Profile</h1>
HTML;
});
$router->get('/data', function($request) {
return json_encode($request->getBody());
});
As you can see, for the routes '/' and '/profile' I am returning some HTML code using heredoc. This is okay but will eventually fill up this file really quickly.
Is there a way to render a template (from inside a subfolder for example) in the space of the 'return html code'?
I assume your second parameter for the get method is a callback function that will be triggered in the function if the route matches? If that's the case I don't see why you return the HTML as it isn't used anywhere. You might want to echo() or print() instead.
If you want to return the code and output it later, you need to save the return value into a variable.
No matter which path you choose, you could use another include() and just put the relevant code into a separate file for each path if you want to make your main script more readable.
I'd also recommend to use require_once instead of include_once in the top as there's no point in continuing execution if these class files are missing.

how to use route to view static apidoc page with laravel

I am currently using http://apidocjs.com/ as my laravel apidoc because I am just used to it before.
to view the apidoc, each time I have to drag the index.html into the browser which is quite annoying.
Is it possible to make it into a static page so people I am sharing the apidoc with can just generate the doc then go to the route.
I tried something like...putting my apidoc folder under public folder of the application and also tried adding a route such as
Route::get('/apidoc', function(){
return File::get(public_path() . '/apidoc/index.html');
});
Both of them didn't work the index.html cannot load the css and js because in index.html the source url is something like vendor/polyfill.js which then tried to go localhost:8000/vendor/polyfill.js but actually the url should be something like localhost:8000/apidoc/vendor/polyfill.js
Does anyone know how to easily fix this?
Thanks in advance for any help
You can "cheat" a little bit by registering the vendor routes as well:
Route::get('vendor/{any}', function ($any) {
abort_unless(is_readable(public_path("apidoc/vendor/$any")), 404);
return File::get(public_path("apidoc/vendor/$any"));
})->where('any', ".*");
Route::get('apidoc', function(){
return File::get(public_path() . '/apidoc/index.html');
});
Of course the ideal solution is if you actually manage to change the template you use for index.html to use relative and not absolute paths (i.e. change all <link href='/vendor...'> to <link href='vendor...'> so the file can automatically request the correct resource.

Laravel framework index.php

I have a project in laravel5 and I have directed virtual host on /public directory. Where should be my main page index.php now? There is some index.php in public folder already but it contains some content that I dont understand. So where should be my index now? Maybe in views?
If you are using Laravel 5.1 then your initial page should be this resources/views/welcome.blade.php.
You can change it to any name. But also you should change the same in your Controller.
Note : If you are rendering the view through controller then you should have the file name like this yourfilename.blade.php
Your views should always inside resources/views/*
The index file stays at the same place, to call a new file that you made, could be with HTML, you can put that file in the view and call it from the controller, hope this is the answer you are looking for.
When a request come to your server, the first file that it is executed is index.php. But this is not the file shown. In Laravel you don't have to force any file be named index.php. So let's imagine that you are trying set up a new index file. You have to use routes.php
routes.php
Route::get("/" , "HomeController#index");
HomeController.php
function index(){
return view("home/index");
}
views/home/index.blade.php
<html>
<head>
</head>
<body>
<p>Index page</p>
</body>
</html>
When a GET request to "/" it's done, the index function of the HomeController it's executed and the view index.blade.php, stored in views/home it's shown.
This it's the basic behaviour of Laravel. So you mustn't rename or move the index.php file in public folder.

Load layout once in Fat-Free Framework

I think this should have a pretty simple explanation but I'm still learning Fat-Free Framework (F3): How do I render only once the header and footer and switch out the content code for the selected route? I have this code:
$f3->route('GET /',
function($f3) {
$f3->set('content','views/welcome.htm');
$f3->set('page_head', 'Welcome');
}
);
And if I add this line:
echo View::instance()->render('layouts/header+footer.htm');
either after the f3->set calls in the route or after $f3->run(); at the end of the index.php file, the whole page refreshes on a route change. I can't call that echo line above before the route code without throwing an error in the content box.
Is there any way to disable the page refreshing? Is it being refreshed because my links are being interpreted as separate pages by the browser? Thanks for any help!
Your question is a little hazy. But I will try to answer in the way I understand.
First your index.php
$f3->route('GET /',
function($f3) {
$f3->set('content','views/welcome.htm');
$f3->set('page_head', 'Welcome');
echo Template::instance()->render('layouts/header+footer.htm');
}
);
$f3->run();
In your header+footer.htm
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>{{#page_head}}</title>
</head>
<body>
<include href="{{#content}}"/>
</body>
</html>
Your views/welcome.htm can contain anything.
<h1>Welcome</h1>
<p>You have arrived to the welcome page</p>
Please remember the folders views and layouts should be in the UI folder
$f3->set('UI','ui/');
On your comment:
You can access the params of a request from $f3->get('PARAMS') or you can do this.
$f3->route('GET /#page',
function($f3,$params) {
$page = $params['page'];
$f3->set('content','views/'. $page .'.htm');
$f3->set('page_head', 'Welcome');
echo Template::instance()->render('layouts/header+footer.htm');
}
);
This should work
If you wish to update only a portion of a web page, without doing a full refresh, then you need to use AJAX.
Start by reading this:
https://fatfreeframework.com/3.6/routing-engine#AJAXandSynchronousRequests
You'll need to use javascript on the front end to make this work. If you don't know how to code this in javascript, then you can start by reading this:
https://www.w3schools.com/js/js_ajax_intro.asp
You may find it easier to use Jquery, which is a very popular javascript library. You can read about it here:
https://www.w3schools.com/jquery/jquery_ref_ajax.asp
Maybe will be not bad to create your own instance of View and extend the main with functionality similar to PHPTal Filters. Then you can set Header in preFilter and Footer in postFilter and extend render() function. The extended render() will render everything together for you including header, footer and body content.
I don't have personally anything against FatFree View but will suggest PHPTal as a templating engine - here simply implementation https://github.com/creoLIFE/FatFree-PHPTAL including Header/Footer served from separate files.

Javascript in an external file

Before I ask this question I must point out that I have tried to search for EVERYTHING!
My question is how can I run javascript from an external file instead of inside my php / html. What I'm trying to do is.
function ClearForm() {
document.form.message.value="";
}
function comeBack(){
if (document.form.message.value == "") {
document.form.message.value="What's on your mind?";
}
}
I have included<script type="text/javascript" src="javascript.js"></script> in the <head> and I have a file in the root called javascript.js and my php file is in the root too so that shouldn't be the problem! But how do I run that pieces of code you see above in the javascript.js file instead of in my php file. It work's fine if I have it in the php file but I want to separate things!
I have also tried to give the form / input field an id and then use getElementById in the external JavaScript file.
But as you can see and hear I'm kinda new to JavaScript so I'm apparently doing something wrong here.
If the above code is the only thing in your Javascript.js file, then you need to call the functions to run the code.
You've included the external Javascript file correctly - however, because all of your JS is included within functions, these function/s must be called before the code will run.
A call to 'ClearForm()' or 'comeBack()' from within your PHP file should run the code.
That JS file will have to be in the same folder as your PHP page.
Test whether the file is found or not by adding this line at the top of the js file
alert('js file found OK!');
document.form is an array, so if you only have one form use:
document.forms[0]
Also depending on which browser you use, find and install some Developer Tools to help you identify these errors.
You have declared those functions in the <head>. All fine.
The question is when do you want to call/run those functions?
If you simply want to run them at the end of the page, then you can add another external javascript file and include it using <script src="my_external_file.js"> right before the </body> tag.
Otherwise, you have to declare onXXX handlers, like onLoad() for the document, onClick() for certain elements, onSubmit() for forms, etc. These, too, can be declared in an external file, but specified after the relevant elements are loaded.

Categories