What's the best way to use Symfony2 to serve AngularJS partials? - angularjs

I'm not sure how I should be serving partials from Symfony to Angular.
I was thinking I should set up a route in Symfony, and then have the controller output the file?
I wasn't sure however how to simply output a file from the controller (i.e. no twig stuff, not really rendering anything, etc.) And will this method cache it properly?
For example,if I want angular to download partials/button.html, should I set up a route like:
partials:
pattern: /web/partials/{partial}
defaults: { _controller: AcmeWebBundle:Partials:show, _format: html }
Then, in my controller have,
...
public function showAction() {
return file_get_contents(' ... path to file ...');
}
....
That obviously doesn't work.. I'm not sure how to output just a straight file without going through twig. Or maybe all my partials should just be twig files (just without any twig stuff in them)?

If you wanted to return the contents like that you would need to add the contents of the file to the response body.
use Symfony\Component\HttpFoundation\Response;
...
public function showAction() {
return new Response(file_get_contents(' ... path to file ...'),200);
}
...
But really you should just let your web server serve the file. What I do is put my partials in a sub folder under the web directory:
web/
partials/
img/
js/
css/
Then just call them domain.com/parials/partialFileName.html and because the file exists symfonys rewrites should ignore it by default and just serve the file.
Another method (mentioned here) is to put the files in your bundle's Resources/public folder, then run
php app/console assets:install --symlink
(where web is the actual directory web/)
This will generate symlinks in the web directory pointing to the public directories. So, if you have:
Acme/DemoBundle/Resources/public/partials/myPartial.html
it'll be available at:
http://www.mydomain.com/bundles/acmedemo/partials/myPartial.html

Related

Is it possible to serve a templated text file using spark? (java web framework)

I am using spark as the backend to a project I am working on. I noticed that spark has the ability to serve templated html, using a templating engine such as velocity, freemaker, etc.
However, this isn't quite what I want. Instead of serving an html template, I would like to serve a plaintext file, while still allowing me to insert parameters where needed. For context, I am trying to allow the user to download code examples based on the parameters they have supplied.
Does anything like this exist, or do I need to essentially build the desired file's content and return it as a string?
Example of what I am trying to do
// example.java
public class Example {
public static void main(String [] args) {
System.out.println( {{ param }} );
}
}
So this ^ would be the plain text template that I am attempting to serve... "param" would be passed to the backend via http request, and inserted into the file. Then I would serve the file to the frontend.
So, (as mentioned in the comment :), glad it helped) you can serve this content as HTML page (then you can use template manager) containing only this plaintext content only. Only exception will be the extension which will be .html instead of .java if the user saves the file.
You could declare a route whose return type is 'text/plain'
get(Main.API_PUBLIC + "/sourcecode", (req, res) -> {
res.status(200);
res.type("text/plain");
return " /* This will be the code snippet you'll be returning */ ";
});
Another alternative would be putting your source code files into the static files directory and link to them in your html.

Spring + Angular + JAR Build with Command Line Parameter

I am building a UI into a JAR for Spring Server. I have a bunch of Angular JS pages. I want to pass in a command line argument to my jar that tells it where the API server is like so:
java -jar application.jar --api=http://ip:9000
So my application.properties file has:
url=${api:http://localhost:9000}
The way I am currently doing is it just having a hardocoded js config file and on each of my .html pages:
<script src="../js/appName/config.angular.js"></script>
Which contains:
var configData = {
url:"http://localhost:9000"
};
And called in each file:
$scope.apiUrl = configData.url;
How do I tap into the applications.properties file that I can override with my JAR command line parameter during runtime vs. the way it has been coded now.
When you pass a value from command line and the same property name is present in properties file then spring boot overrides the value from command line. So to achieve what you want do something like this
In application.properties
#this is default value
app.url=localhost:8080
Create a class to map the properties value or you can use existing class or something else based on your project structure.
#Component
public class Sample {
#Value("${app.url}")
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Now when your execute a jar with argument --app.url="someserver:9090" the value will be overriden and you can use this value anywhere.
Note it will also work if you try to access the properties value directly in jsp using expression.
Try it, it works. I have used the same thing in my latest project which is a composite microservices and each component need each others url.
[Edit]
Reference : http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
Am I getting it right: The client part is delivered by the application? So the part of the last sentence 'during runtime' has more the meaning of 'bootstrap/initial loading', right? One (old school) approach is to provide the entry html (e.g. index.html) through the application (a simple template engine) and provide the needed information with a setter in a JS config object:
// pseudo js code with thymeleaf
<script th:inline="javascript">
/*<![CDATA[*/
myConfig.url = [[${#httpServletRequest.remoteHost}]];
/*]]>*/
</script>
This is just a sample that will only set the remote host name but I think you get the idea.
Side note: I still don't really get why do you have to set this. If the application contains the client code, why do you work with absolute URLs for remote calls? (Disclaimer: I have only experience in Angular(2) and not with AngularJS)

AngularJS application with different customizations

I got a "framework" created by us using AngularJS. It allows to build questionnaire system and it has many different parameters that control the behavior of framework.
Using this framework we've created 2 projects: projectA and projectB. The difference between these projects are the settings and assets (css, img, ...)
Both projects are stored on the same branch in git and only config file defines the project customization.
I can't think of the best way how these 2 projects can be easily deployed separately from the same code source using Gulp or something other.
Here are some ideas I got for the moment:
1. Have both settings files and images (e.g. logo_A.png and logo_B.png) in the code and choose appropriate during build using Gulp
2. Create folder customizations that will have 2 subfolders A and B with corresponding settings and assets
3. Create separate repository for each project installation scripts (not the code) and these scripts will do all the work
What is the best way in this case?
Finally, the easieast and most understandible solution was to create additional custom folder.
Assets
In addition to normal application files I got now custom folder with 2 subfolders: A and B each of them containing assets (css, img) that correspond only to concrete project.
In gulp I've used yargs module which allows to pass parameters. After reading project name from input I can looks inside custom folder to see if there are resources interesting for me (I've just added custom folder into the resources paths).
var customPath = './custom/' + app.name;
exports.paths = {
web: {
//Resources
styles: ['./app/**/*.css', './app/**/*.scss', customPath + '/**/*.css', customPath + '/**/*.scss'],
...
And the call to build task now looks like this: gulp build --name A.
Configuration
One more thing was done for configuration file of AngularJS that contains constants. I've used gulp-ng-config plugin which allows to build AngularJS configuration (constants) file on fly. In my flow, first I check if custom configuration file exists inside custom folder I use it, if no I'm using default one from application.
var getAppScripts = function() {
return $.eventStream.merge(
gulp.src(config.paths.web.scripts)
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
//.pipe($.eslint())
.pipe($.eslint.format()),
getAppConfig())
.pipe($.angularFilesort());
};
var getAppConfig = function() {
var configFile = config.paths.web.custom + "/app.config.yaml";
if (fs.existsSync(configFile)) {
return gulp.src(configFile)
.pipe($.ngConfig(config.app.name, {
parser: 'yml',
createModule: false
}));
}
else {
return gulp.src(config.paths.web.config);
}
}

Laravel returning a 404 on an image

This should be fairly simple though it is completely stumping me.
I have a backend Laravel installation running on localhost:8000
I have a front end Angular app running on localhost:9001.
I have some 'static' images I have included in my seed data (eg.
'1', 'user.png'), these images are being rendered perfectly in my front end (they are also served from the exact place my image uploads are going).
The URL I am currently serving images from is http://localhost:8000/images/{filename}
I can upload images from the front to the back end and they appear in the DB and the image is being put in the filesystem, I'm populating the correct URL in my front end (as evidenced by the previous URL).
My uploaded images are not being shown.
In my logs I am getting:
[2015-01-20 18:13:49] local.ERROR: NotFoundHttpException Route: http://localhost:8000/images/j249ae747ce28c317e02f1fb6d0a10c3.jpg [] []
[2015-01-20 18:13:49] local.ERROR: exception 'Symfony\Component\HttpKernel\Exception\NotFoundHttpException'
I tried a method in my routes file, but couldnt see why, when I am already serving some images already?
I have also set all permissions to 755 on my /images folder.
Any ideas?
I'm not sure I follow every bit of multi-system interaction you have going on, but I'd drop back to first HTTP principles.
Try accessing the image URL directly.
http://localhost:8000/images/j249ae747ce28c317e02f1fb6d0a10c3.jpg
If the error in your browser (or your logs, if you're not developing with debug set to true) is
local.ERROR: NotFoundHttpException Route: http://localhost:8000/images/j249ae747ce28c317e02f1fb6d0a10c3.jpg
This means your web server couldn't find a file at images/j249ae747ce28c317e02f1fb6d0a10c3.jpg, and handed the request to Laravel. This means you need to figure out why your webserver can't see the file.
Assuming you're serving index.php from the public folder
Do you have a public/images/j249ae747ce28c317e02f1fb6d0a10c3.jpg file?
Are you sure? Copy and paste the path into terminal and to a ls public/images/j249ae747ce28c317e02f1fb6d0a10c3.jpg to make sure your brain isn't missing some subtle case issue
Are any errors showing up in your web server's logs (not Laravel's)
Can you create a text/html file in the images folder and serve it? If not, then you may not be pointing your web server at the folder you think you are.
Something like
http://localhost:8000/images/test.txt
http://localhost:8000/images/test.html
Some first principles debugging like that should point you in the right direction.
rm public/storage
php artisan optimize:clear
php artisan storage:link
This worked for me.
The problem is you haven't generated a url for your uploaded image
Try accessing your url like this
http://localhost:8000/storage/images/j249ae747ce28c317e02f1fb6d0a10c3.jpg
To generate the above url
Add this method \Storage::disk('public')->url(); method in your controller.This method accesses the public disk array which is found in Config\filesystems.php and it generates a url in the following format
http://localhost:8000/storage/images/j249ae747ce28c317e02f1fb6d0a10c3.jpg
For example the method below stores the image in the image folder and generates the url of the image path.
public function uploadImage(Request $request)
{
$request->validate(['image'=>'file|image|max:5000']);
$imageProfile = new ImageProfile();
if($request->hasFile('image') && $request->file('image')->isValid())
{
$image = $request->file('image')->store('images');
$imageProfile->image_profile_url = \Storage::disk('public')->url($image);
$imageProfile->save()
}
return response()->json($imageProfile,200);
}
The code returns a Json response below
{
"id": 13,
"image_profile_url ": "http://127.0.0.1:8000/storage/images/cxlogqdI8aodERsmw74nmEx7BkxkWrnyJLMH7sFj.jpeg",
"updated_at": "2020-01-13 16:27:37",
"created_at": "2020-01-13 16:27:37",
}
Try to copy the url and test it in postman.
Visit the link to learn more about Laravel file storage
Laravel File Storage
Hope it helps.
laravel 8
Controler function
public function store(Request $request)
{
$this->validate($request, [
'site_title' => 'required',
'logo_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$input['logo_image'] = time().'.'.$request->logo_image->getClientOriginalExtension();
$request->logo_image->move(public_path('images'), $input['logo_image']);
$input['site_title'] = $request->site_title;
//dd($input);
Site_settings::create($input);
return back()->with('success','Image Uploaded successfully.');
}
blade view
<td>
<img src="{{ url('/images/').'/'.$site_settings->logo_image ?? '' }}" alt="" width="250px" height="auto">
</td>

CakePHP generate a Document to Webroot

I'm currently working with cakephp and I am generating a word document. My problem is how can I put the generated document on my web root and not as a download.
I am guessing you are using an action to generate a document, which gets output to the browser.
You should either use output buffering to "catch" the output and then write it to a file, or write the document data to a string, and write that string to a file on the server.
EDIT:
PHPWord has a SAVE method. In your action, you can save the document to a certain location, but output something else, i.e. success notification. This way, your action only generates the file:
public function generateWordDocument(){
//... your word file creation...
$wordDocumentLocation = TMP . 'word_files/';
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save($wordDocumentLocation . 'helloWorld.docx');
$this->Session->setFlash('Document generated!');
$this->redirect(array('action'=>'index')); //or wherever you want
}
If you want to protect that file, you could save the file to a "secure" folder (this can either be a folder outside the "app/webroot" folder, or a folder protected with .htaccess deny all instruction) and than use another action, like "getWordDocument":
function getWordDocument($documentName){
$wordDocumentLocation = TMP . 'word_files/';
if (file_exists($wordDocumentLocation . $documentName)) { //this is not really the safest way of doing it
$fp = fopen($wordDocumentLocation . $documentName, 'rb');
header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");
header("Content-Length: " . filesize($wordDocumentLocation . $documentName));
fpassthru($fp);
exit();
}
}
Please note, that this code is just for "grasping the concept" and is in no way safe or optimal.
i think you want to add file in webroot but it is not downloadable for public users ,
You have several ways :
- protect folders with .htaccess (Like Js folder)
- create new folder in app folder like webroot and put files in it
- use Dispatcher Filters in cakephp : http://book.cakephp.org/2.0/en/development/dispatch-filters.html
and ....

Resources