In Part 1, we set up gulpjs and browser-sync to build a static site generator.
In this part, we will set up a template engine called Nunjucks and set up a base template.

Installing Plugins

Let’s start by installing the plugins in our project. In our command line, type the following.

$ npm install --save-dev gulp-nunjucks-render

About Nunjucks

Nunjucks allows us to break our html into smaller reusable pieces that we can use in other html files. We can even inject data to populate our html files. If you have used Flask, you’ll notice the markup is inspired by Jinja2.

Creating a Template

We’ll copy our app/index.html file to app/templates/base.html.
Then, we’ll make a pages directory and move the index.html to app/pages/index.html

$ cp app/index.html app/templates/base.html
$ mv app/index.html app/pages/index.html
  Folder Structure
├── app
│   └── templates
│       └── base.html
|   └── pages
│       └── index.html
├── gulpfile.js

We’ll change the markup for base.html to become a Nunjucks template.

<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>
      {% block title %} {% endblock %} <!-- we'll change the title -->
    </title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  </head>

  <body>

    <div class="container container-fluid">
      {% block content %} <!--- Our content will be here -->
      {% endblock %}
    </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 -->
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  </body>
</html>

Let’s change the index.html to take advantage of our new base.html nunjucks template.

<!-- index.html -->
{% extends "base.html" %} <!-- we're extending the base template -->

{% block title %}This is the new title of our webpage{% endblock %}

{% block content %}
<h1>Hello<h1>
<p>
  We just extended the base template. Anything we put in the content blocks will
  be specific to the index.html page.
</p>
{% endblock %}

Integrating Gulpjs and Nunjucks

Now that we have our template and pages file ready.
We’ll import the plugin and write a gulp task for it

// gulpfile.js
var gulp              = require('gulp');
var browserSync       = require('browser-sync');
var nunjucksRender 		= require('gulp-nunjucks-render'); // importing the plugin

gulp.task('serve', function() {
    console.log('running server');
    browserSync({
        server: {
            baseDir: 'app'
        }
    });
});

// writing up the gulp nunjucks task
gulp.task('nunjucks', function() {
  console.log('nunjucking');

  // configuring the templates folder for nunjucks
  nunjucksRender.nunjucks.configure(['app/templates/']);

  // get the pages files
  return gulp.src('app/pages/**/*.+(html)')
    .pipe(nunjucksRender())
    .pipe(gulp.dest('app'))
});

//default task to be run with gulp
gulp.task('default', ['serve']);

Running Nunjucks

Now, we can run the nunjucks task and then the serve task to see our changes.

$ gulp nunjucks
$ gulp serve

Results

Nunjucks took our base template and index file and turned it into a fully compiled html page.
We can make as many pages files as we want and the nunjucks task will compile them into static files.
We can combine the nunjucks and serve commands as another task, but we’ll save it for another tutorial.
You can check out our changes on Github.

I wanted to create a static site without having to copy and paste the header/footer and other common snippets.
There’s lots of tools that would do this including Jekyll (ruby) or Pelican (python), but I wanted something fast and easy to work with.
I figured I could use gulp.js with plugins to create the same type of static site generator as the above two.
Let’s start by installing gulp and browser-sync and creating an index page to display.

Installing Plugins

Let’s start by installing the plugins in our project. In our command line, type the following.

$ npm init
$ npm install gulp browser-sync --save-dev

Folder Structure

Let’s create two folders in our project folder called app/ and a file, gulpfile.js
Our Folder Structure

├── app
├── gulpfile.js

Browser Reloading

We are installing a tool called browser-sync which watches our files and automatically reloads the server, so that we do not need to constantly refresh the page. Let’s edit our gulpfile.js to look like the file below.

// gulpfile.js
var gulp        = require('gulp');
var browserSync = require('browser-sync');

gulp.task('serve', function() {
    browserSync({
        server: {
            baseDir: 'app' // Change this to your web root dir
        }
    });
});

// Default task to be run with `gulp`
gulp.task('default', ['serve']);

The first two ‘var’ lines are importing our plugins. The ‘gulp.task’ functions are running our gulp tasks. One which includes running browser-sync, and the other will default to the first task without any additional command line parameters.

Let’s set up our index page in the app folder. I grabbed the default bootstrap demo site.

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <h1>Hello, world!</h1>

    <!-- 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="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  </body>
</html>
  Folder Structure
├── app
|    ├── index.html
├── gulpfile.js

Running Commands

In the terminal, run the command ‘gulp’ or ‘gulp serve’ and it should open a browser window with the index.html page shown.
If you leave gulp running and change the index.html page, it will automatically reload and show you your edits.

You can see what we currently have on Github.

Check out Part 2 on building a static site generator with gulp.

Fixing iPhone Lag

November 20, 2015 — Leave a comment

The iPhone can get sluggish and laggy after a while. iOS doesn’t have a button to you can tap to shutdown all apps and free the RAM.

But there’s a quick trick to force your iPhone to free up it’s RAM without a new app to download.

 

  1. Hold the Sleep  / Wake button until you get the “slide to power off” screen.
  2. Release the the Sleep Wake Button.
  3. Now hold the Home button until it goes back to the home screen.

Once the iOS home screen is displayed, the iPhone’s RAM flush should be completed.

Easy orientation change detection for Ionic Apps or mobile web apps.

window.addEventListener("orientationchange", 
    function() {
        if (window.orientation == 90 || window.orientation == -90) {
            alert('landscape mode');
        } else {
            alert('portrait mode;);
        }
    }, false);

Of course you should go to University and study whatever you want. Of course you should find your passion, however long it takes. You can be whatever you want. You can do whatever you want. Post secondary education is an investment in your future.

But maybe spending $100,000 and eight-years of your life on that double-major in history and fine arts, only to spend the next few years working as a Starbucks barista, wasn’t the wisest use of your time and money.

Of Course, But Maybe…

DIY can be seen as a side-hustle to make more money. Now there’s zero excuse for folks who are unwilling to moonlight, start a side business, or create a product to generate passive income. You can simply increase the amount of DIY projects, like cleaning, to earn more money by saving money.

If you love money, you will probably be better at accumulating more money. You’ll do a lot more research on how wealthy people got rich, what to invest in the stock market, how to get a raise, and all sorts of money attracting stuff.

It’s OK to Love Money

If you’ve ever had a big idea and thought, “There’s no way I can make time for it,” there are a lot of real-life stories that say, “Yes, you can.”

Craigslist, Spankx, GitHub, Basecamp were all side projects. Wake up earlier or sleep later. You have to prioritize what’s important.

The Craigslist Method

Put this one liner in terminal to stop Android File Transfer from autostarting on OSX whenever you plug in your Android device.

PID=$(ps -fe | grep "[A]ndroid File Transfer Agent" | awk '{print $2}'); if [[ -n $PID ]]; then kill $PID; fi; mv "/Applications/Android File Transfer.app/Contents/Resources/Android File Transfer Agent.app" "/Applications/Android File Transfer.app/Contents/Resources/Android File Transfer Agent DISABLED.app"; mv "${HOME}/Library/Application Support/Google/Android File Transfer/Android File Transfer Agent.app" "${HOME}/Library/Application Support/Google/Android File Transfer/Android File Transfer Agent DISABLED.app"; osascript -e 'tell application "System Events" to delete every login item whose name is "Android File Transfer Agent"'

Credit goes to monkeyhybrid

Since ‘brew bundle’ has been deprecated, here is a temporary fix.

Create a file named brew-bundle and write the code below.

#!/usr/bin/env sh
[ -f "Brewfile" ] || (echo "No Brewfile found" 1>&2 && exit -1)
while read line
do
  [ "${line###*}" ] && brew $line
done < Brewfile

Place file in ~/bin/ and chmod +x ~/bin/brew-bundle

You’re now able to use your Brewfile again.

I have just read The 4-Hour Workweek by Tim Ferris. Great book on lifestyle automation.
Here’s some notes I took on the book while reading.

– Limit tasks to the important to shorten work time (80/20 rule)
– Shorten work time to limit tasks to the tasks to the important (Parkinson’s Law)
Using a shorter deadline will force you to focus on execution.
Identifying the critical tasks and scheduling them with very short and clear deadlines is the best solution for becoming productive and efficient.

Ask yourself:
– Am I being productive or just active?
– Am I inventing things to do to avoid the important?

Compile a todo list that is not computerized for the next day. There should be never more than 2 items to complete each day. If there is, you must ask yourself “If this is the only thing I accomplish, will I be satisfied with today?”

Propose solutions to everyday questions, instead of asking for opinions.

I. Low information diet
A. Selective ignorance
i. Problems solve themselves or disappear if you remove yourself as a bottleneck and empower others.
ii. Increased output demands decreased input.
B. Actions
i. One week information fast; no news, no television, no unnecessary web browsing.
ii. Catch up news by asking colleagues
iii. Information should be used immediately and stored if it is important.
iv. Focus on “on-time” information and not “just-in-case”
C. Challenge
i. Ask random strangers for their number. The goal is to get out of your comfort zone.
II. Interrupting Interruptions and the Art of Refusal
A. Assertiveness
i. Learn to be difficult when it matters.
ii. Having a reputation for being assertive will give you preferential treatment.
B. Time wasters
i. It is your job to train those around you to be effective and efficient.
ii. Keep meetings less than 30 minutes, and have defined goals and objectives.
C. Time consumers: batch and do not falter
i. Batch same types of tasks together.
ii. Estimate the the value of your time and the amount of time you save by batching tasks.
iii. Calculate how much you earn by multiplying the amount of time saved by your per hour rate for different batching frequencies: 1 time per week, two weeks, month.
iv. If problems creating by batching tasks together cost more than the hours saved, scale back to less frequent schedule.
D. Empowerment Failures: Rules and readjustment.
i. Try not to micromanage.
ii. People are smarter than you think. Give them a chance to prove themselves.
iii. Empower others to act without interrupting you. Give them permission.
iv. Set rules in your favor. Limit access to your time.
III. Income Automation
A. The Renaissance Minimalist
i. Cash flow and times, without these two things, nothing is possible.
ii. The more resellers there are, the fast your product goes extinct.
iii. The more middlemen are involved, the higher your margins need to be.
B. Begin with the end in mind.
i. Find a market, define customers, then find/develop a product for them.
ii. Aim for a 8-10x markup
iii. Price range of $50-200 per sale provides most profit for the last customer service hassle.
iv. Should take no more than 3-4 weeks to manufacture
v. Options: Resell a product, license a product, create a product
C. Credibility snowball
i. Join two or three related trade organizations
ii. read the three top selling books
iii. give one free one-to-three hour seminar.
iv. offer to write one or two articles for trade magazines.
D. Art of Undecision
i. Fewer Options = More revenue
ii. Customer service is providing excellent product at reputable price and solving legitimate problems in the fastest manner possible.
iii. The more options, the more indecision created and fewer orders received.
iv. The more options, the more manufacturing and customer service is needed.
a. offer one or two purchase options.
b. do not offer multiple shipping options, offer one fast method and charge premium.
c. eliminate phone orders and direct to online ordering.
d. do not offer international shipments.
v. Policies towards low maintenance customers and attracting high profit.
a. Do not accept via western union, checks or money orders.
b. raise wholesale minimums to 12-100 units and require tax id number.
c. refer all potential resellers to an online form.
d. never negotiate pricing or approve lower pricing for higher volume orders, cite company policy.
e. offer low priced products instead of free products to capture information for follow up sales.
f. offer a lose-win guarantee.
g. Do not accept orders from common mail fraud countries.
IV. How to look Fortune 500 in 45 minutes.
A. Don’t be the CEO or Founder.
i. give yourself a mid level vp. For negotiation purposes, do not appear to be the ultimate decision maker.
B. Put multiple email contacts on the website.
C. Set up an interactive voice response remote receptionist.
D. do not provide home address