I am trying to use php inside .html file with gulp-connect-php on windows - gulp-watch

I am new to gulp and trying to use php inside .html file with gulp-connect-php on windows.
The html file is included the code
<?php echo "test"; ?>.
But, It does not appear "test" on the browser. So, could you tell me how to solve this problem?
The below is my gulpfile.js. Any assistance will be appreciated. Thanks in advance:
var gulp = require("gulp");
var browser = require("browser-sync");
var connect = require("gulp-connect-php");
gulp.task("server", function() {
connect.server({
bin:'c:/xampp/php/php.exe',
ini:'c:/xampp/php/php.ini',
port:3000,
base:'./www'
}, function(){
browser({
proxy:'localhost:3000'
// server: {
// baseDir: "./"
// }
});
});
});
gulp.task("reload", function() {
browser.reload({stream:true});
});
gulp.task("default",['server'], function() {
gulp.watch("./*.php",["reload"]);
});

I had same problem.
I added router: '. /router.php' parameter to connect.server({.
gulp-connect-php runs a php Built-in web server internally.
It can set the router script for the php Built-in web server by adding the router parameter.
Built-in web server:
https://www.php.net/manual/en/features.commandline.webserver.php
connect.server({
bin:'c:/xampp/php/php.exe',
ini:'c:/xampp/php/php.ini',
port:3000,
base:'./www',
router: './router.php'
}, function(){
router.php
<?php
$path = $_SERVER["SCRIPT_FILENAME"];
if(preg_match("/\.html$/", $path)){
chdir(dirname($path));
return require($path);
}
return false;
?>

Related

Change script type to "text/babel" using requireJS

I am using requireJS to load React components but I was getting the error "Uncaught SyntaxError: Unexpected token <" because the script type for the file is "text/javascript" instead of "text/babel". To solve this I have tried to set the scriptType as explained by requireJS docs and explained in this question, but I'm unable to get it working or find a good example of how to make this work.
requireConfig.js:
requirejs.config({
baseUrl: 'scripts/',
paths:
{
jquery: 'jquery-1.9.0',
react: 'libs/build/react',
reactdom: 'libs/build/react-dom',
browser: '//cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min',
inputWindow: 'inputWindow/inputWindow'
},
scriptType: {
'inputWindow': "text/babel"
}
});
define(function (require) {
var InputWindow = require('inputWindow');
InputWindow.initialize();
});
inputWindow.js:
define(function(require){
var React = require('react');
var ReactDOM = require('reactdom');
var InputWindow = React.createClass({
render: function(){
return(<div>
{this.props.message}
</div>)
}
});
function initialize(){
ReactDOM.render(<InputWindow message="Hello World!"/>, document.getElementById('inputWindowDiv'))
}
return {
initialize: initialize,
}
})
When I configure requireConfig.js with the section
scriptType:{
'inputWindow':'text/babel'
}
then the file inputWindow.js is loaded into index.html with the tag
type="[Object Object]"
until requireJS times out.
screen capture of inputWindow.js loaded with type=[Object Object]
Instead of
scriptType: {
'inputWindow': "text/babel"
}
try
scriptType: 'text/babel'
It should work. Right now you're trying to stringify an object so no wonder it doesn't work. ;)

Reload angular-translate-static-loader-files within app, without refresh in Ionic

I'm working on this Ionic app and I'm using angular-translate-loader-static-files with angular-translate to load in a bunch of language .json files.
Everything is working fine, but I'm trying to figure out how to basically "re-run the $translateProvider" so it can reload all the static files all over again as the .json files will get updated from the server periodically. I have yet to figure this out, and even trying to force a "page reload" doesn't cause the static files to reload.
I should note that I'm currently testing this in iOS and I realize that the directory structure will change, based on OS.
Here is my service that utilizes $cordovaFile to overwrite the file with new text. Right now I'm just using a simple json string to make sure I can solve the problem:
(function() {
'use-strict';
angular.module('coursemill.services')
.service('Translations', Translations);
/**
* Service: Check network connection
*/
function Translations($cordovaFile) {
function updateLanguageFile(lang) {
document.addEventListener("deviceready", function() {
$cordovaFile.checkFile(cordova.file.applicationDirectory + "/www/languages/", lang + ".json")
.then(function (success) {
// Update the language file
$cordovaFile.writeFile(cordova.file.applicationDirectory + "/www/languages/", lang + ".json", '{"COURSES_MENU_REQUIRED": "Required"}', true)
.then(function (success) {
// TO-DO: reload translation files
},
function (error) {});
},
function (error) {});
});
}
return {
updateLanguageFile: updateLanguageFile
}
}
})();
Here is a snippet from my .config:
// Setup the language translations
$translateProvider.useStaticFilesLoader({
prefix: 'languages/',
suffix: '.json'
});
Here is a snippet from my controller:
Translations.updateLanguageFile('en_US');
When I open the file up after this function has been run, the contents of the file are replaced and are doing exactly what I want, but I'd like my language variables inside the app to be updated as well, and they aren't.
Any thoughts on what can be done here?
Doink, I needed to use $translate.refresh() in my service function. So now it looks like this:
(function() {
'use-strict';
angular.module('coursemill.services')
.service('Translations', Translations);
function Translations($cordovaFile, $translate) {
function updateLanguageFile(lang) {
document.addEventListener("deviceready", function() {
$cordovaFile.checkFile(cordova.file.applicationDirectory + "/www/languages/", lang + ".json")
.then(function (success) {
// Update the language file
$cordovaFile.writeFile(cordova.file.applicationDirectory + "/www/languages/", lang + ".json", '{"COURSES_MENU_REQUIRED": "Required"}', true)
.then(function (success) {
// Reload translation files
$translate.refresh();
},
function (error) {});
},
function (error) {});
});
}
return {
updateLanguageFile: updateLanguageFile
}
}
})();

Using Express to render an .ejs template for AngularJS and use the data inside AngularJS $scope

I hope I can explain myself with this first question I post on Stack Overflow.
I am building a small test application with the MEAN stack.
The application receives variable data from Mongoose based on an Express Route I have created.
For example the url is: localhost:3000/cities/test/Paris
Based on the name of the city the response gives me the name of the city and a description. I Know how to get this data inside the .ejs template
But thats not what I want. I want to use this data inside an ngRepeat.
Maybe this is not the right way but maybe you can help me figure this out.
The reason I want to do this is because I don't want a single page application but an Angular template that can be used over and over for each city and only uses the data that gets back from the mongoose find() results and not the whole cities array.
app.js :
var cityRoutes = require('./routes/cities');
app.use('/cities', cityRoutes);
app.set('views', './views'); // specify the views directory
app.set('view engine', 'ejs'); // register the template engine
./routes/cities/cities.js :
var express = require('express');
var citiesList = require('../server/controllers/cities-controller');
var bodyParser = require('body-parser');
var urlencode = bodyParser.urlencoded({ extended: false });
var router = express.Router();
// because this file is a fallback for the route /cities inside app.js
// the route will become localhost:3000/cities/test/:name
// not to be confused by its name in this file.
router.route('/test/:name')
.get(citiesList.viewTest)
module.exports = router;
../server/controllers/cities-controller.js :
var City = require('../models/cities');
module.exports.viewTest = function(request, responce){
City.find({ stad: request.params.name }, function(err, results){
if (err) return console.error(err);
if (!results.length) {
responce.json( "404" );
} else {
responce.render('angular.ejs', { messages:results });
// through this point everything works fine
// the angular.ejs template gets rendered correctly
// Now my problem is how tho get the results from the
// response.render inside the Angular directive
// so I can use the data in a $scope
}
});
};
../models/cities.js
var mongoose = require('mongoose');
module.exports = mongoose.model('City', {
stad: { type: String, required: true },
omschrijving: String
});
AngularJS directive :
// This is where I would like to use the messages result data
// so I can create a $scope that handles data that can be different
// for each url
// so basically I am using this directive as a template
app.directive('bestelFormulier', function () {
return {
restrict: 'E',
templateUrl: '/partials/bestel-formulier.html',
controller: ['$scope', '$http', '$resource', '$cookieStore',
function($scope, $http, $resource, $cookieStore){
// at this point it would be nice that the $scope gets the
// url based results. But I don't now how to do that..
// at this point the var "Cities" gets the REST API with
// all the cities...
var Cities = $resource('/cities');
// get cities from mongodb
Cities.query(function(results){
$scope.cities = results;
//console.log($scope.products);
});
$scope.cities = {};
}],
controllerAs: 'productsCtrl'
}
});
The database is stored like this :
[
{
stad: 'Paris',
omschrijving: 'description Paris',
},
{
stad: 'Amsterdam',
omschrijving: 'description Amsterdam',
}
]
I hope these files included helps explaining my issue.
Thanks in advance for helping me out
I figured out a way to do it...
The following changes to my code fixed my issue.
in app.js
var cityRoutes = require('./routes/cities');
app.use('/', cityRoutes);
// removed the name cities
./routes/cities/cities.js :
router.route('/cities/test/:name')
.get(citiesList.viewTest)
// added this route to use as an API
router.route('/api/cities/test/:name')
.get(citiesList.viewStad)
../server/controllers/cities-controller.js :
// added this callback so that a request to this url
// only responses with the data I need
module.exports.viewStad = function(request, responce){
City.find({ stad: request.params.name }, function(err, results){
if (err) return console.error(err);
if (!results.length) {
responce.json( "404" );
} else {
responce.json( results );
}
});
};
in my AngularJS app I added the $locationDirective and changed the following in my Angular directive to :
var url = $location.url();
var Cities = $resource('/api' + url);
// now when my .ejs template gets loaded the Angular part looks at
// the current url puts /api in front of it and uses it to get the
// correct resource
That is the way how I can use it in my $scope and use al the lovely Angular functionality :-)
Hope I can help other people with this... Eventually it was a simple solution and maybe there are people out there knowing beter ways to do it. For me it works now.

How to get tests to record fixtures with AngularJs like vcr in Rails?

I've been looking everywhere, I tried node-replay but with protractor but it won't work with selenium.
I've also tried vcr.js and sepia.
How do I go about setting up my tests for that they make the initial calls but store them as cassettes like vcr.
Cheers.
I've been setting up sepia to be used with protractor.
It works now, here is what I did:
I assume you've already set up grunt-connect to run your protractor tests.
Then you'll need to wait for the event listening event from the connect configuration:
grunt.event.once('connect.test.listening', function)
And that's where you will configure sepia.
grunt.event.once('connect.test.listening', function(host, port) {
/**
* Configure sepia here
*/
var sepia = require('sepia').withSepiaServer();
// Use your custom configuration
sepia.configure({
verbose: true,
debug: true,
includeHeaderNames: false,
includeCookieNames: false
});
// I have some path/body content to filter configured in the vrc configuration
var bodyFilters = grunt.config('vcr.filters.body') || [];
var pathFilters = grunt.config('vcr.filters.path') || [];
var regexPath = function(string) {
var escapedString = string.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
return new RegExp(escapedString);
};
// Filter path
_.map(pathFilters, function(filter) {
sepia.filter({
url: regexPath(filter.path),
urlFilter: function(url) {
return url.replace(filter.pattern, filter.replacement);
}
});
});
// Filter body content
_.map(bodyFilters, function(filter) {
sepia.filter({
url: regexPath(filter.path),
bodyFilter: function(body) {
return body.replace(filter.pattern, filter.replacement);
}
});
});
});
});

how to get clipboard data in angular JS

I was actually looking to get the content of clipboard using angular JS to simulate a copy paste thing.
I created a directive for copy to clipboard which is using the document.execCommand() method.
Directive
(function() {
app.directive('copyToClipboard', function ($window) {
var body = angular.element($window.document.body);
var textarea = angular.element('<textarea/>');
textarea.css({
position: 'fixed',
opacity: '0'
});
function copy(toCopy) {
textarea.val(toCopy);
body.append(textarea);
textarea[0].select();
try {
var successful = document.execCommand('copy');
if (!successful) throw successful;
} catch (err) {
console.log("failed to copy", toCopy);
}
textarea.remove();
}
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.bind('click', function (e) {
copy(attrs.copyToClipboard);
});
}
}
})
}).call(this);
Html
<button copy-to-clipboard="Copy Me!!!!" class="button">COPY</button>
here's a concise version I use -
function copyToClipboard(data) {
angular.element('<textarea/>')
.css({ 'opacity' : '0', 'position' : 'fixed' })
.text(data)
.appendTo(angular.element($window.document.body))
.select()
.each(function() { document.execCommand('copy') })
.remove();
}
BTW, if using Angular to copy to clipboard with a Chrome Packaged App, do the following:
Add "clipboardRead" and "clipboardWrite" to the "permissions" in the manifest.json.
use ng-click in your view to feed the value to the controller $scope, like: data-ng-click="copyUrlToClipboard(file.webContentLink)"
Put a function in your controller like:
$scope.copyUrlToClipboard = function(url) {
var copyFrom = document.createElement("textarea");
copyFrom.textContent = url;
var body = document.getElementsByTagName('body')[0];
body.appendChild(copyFrom);
copyFrom.select();
document.execCommand('copy');
body.removeChild(copyFrom);
this.flashMessage('over5');
}
I had the same issue and I used angular-clipboard feature[1] which uses new Selection API and Clipboard API available in the latest browsers.
First we have to install angular-clipboard lib, i'm using bower.
$ bower install angular-clipboard --save
To import the module use following in html.
<script src="../../bower_components/angular-clipboard/angular-clipboard.js"></script>
To set values to element using $scope in controller
$scope.textToCopy = 'Testing clip board';
Load the clipboard module using,
angular.module('testmodule', ['angular-clipboard']);
This works for Chrome 43+, Firefox 41+, Opera 29+ and IE10+.
Its simple & worked fine.
[1] https://www.npmjs.com/package/angular-clipboard
Thanks,
A completely different approach:
I need to copy & paste text between windows, so I used this to save (copy) the data to local storage. Then, in the other window, I load it out of local storage, using the same key, and I can then 'paste' is as I like.

Resources