Cristian Vasta

Cristian Vasta

1574300565

How to create a Website using Nuxt.js and Contentful

As a frontend-developer, working with static-site-generators and serverless architecture is a joy, and with it, we can create very powerful and amazing applications which we can also server-side render

This article aims to give you a step by step guide for building a very basic website using Nuxtjs + Contentful — Including a simple Vuex example.

Find the full GIT repo here:
https://github.com/nickycdk/nuxt-contentful-example

Personally, my own website is running on a Nuxt/Contentful setup with Continuous deployment by connecting my GIT repo with Netlify, this combined with Contentful’s webhooks to rebuild your site automatically when publishing new content is just…. Awesome

What is Nuxt

If you’ve built Vue applications before, you’ve probably heard about NuxtJS, which is the equivalent to what NextJS is for React.

Nuxt is a framework that builds on top of Vue that simplifies the development of universal or single page Vue apps, which is great if you are building a website and want to make sure it can get indexed by Google.

What is Contentful:

Contentful is known as a headless CMS system, which means it is a API-First content-management-system from where you can create, manage and distribute content to any platform or device.

Learn much more about Contentful on their own website right here: https://www.contentful.com/

In this article you’ll learn how to build a very simple nuxt website that pulls data from Contentful. Once you’ve gotten a grasp of both and how you can use these two together, you can really start build powerful and amazing applications.

Nuxt Setup

Before we can start building, we need to install Nuxt. We’ll do that by using the VueCLI. If you haven’t installed this on your system before, you need to install it by using the terminal:

npm install -g vue-cli

Now you can use the VueCLI to setup a Nuxt project.

vue init nuxt/starter nuxt-contentful-demo

Follow the instructions and give the project a name, description and author.

This is image title

When done, cd into the folder of you project and run

npm install
npm run dev

Beautiful 😊 We’re now one step closer and we have a foundation to build upon.

Contentful Setup

Go to Contentful and login with your username and password.
If you haven’t already got a user, you need to create one to be able to use Contentful. They have a free plan which you can use.

Once logged in, first thing we need to do is setup a new space for our website.

When you’re in Contentful, click on “Create space”

This is image title

When creating a new space, we’ll need to fill in a few details.
Choose the free plan and give your space a name and confirm the creation.

This is image title

Integrate Contentful into the Nuxt

When wanting to use Contentful in in Nuxt projects, we need to install the javascript SDK. We can do this by running the following command:

npm install --save contentful

When done installing, we can go to our project in our IDE, and create a new file under “plugins”. This will be basically be the file that are telling Nuxt to use contentful as a plugin, which enables us to easily fetch our data from Contentful.

Go ahead a create a new file:

This is image title

const contentful = require('contentful');

// use default environment config for convenience
// these will be set via `env` property in nuxt.config.js

const config = {
  space: process.env.CTF_SPACE_ID,
  accessToken: process.env.CTF_CDA_ACCESS_TOKEN
};


// export `createClient` to use it in page components
module.exports = {
  createClient () {
    return contentful.createClient(config)
  }
}

As you might have noticed we are referencing some environment variables that we haven’t created yet.

const config = {
  space: process.env.CTF_SPACE_ID,
  accessToken: process.env.CTF_CDA_ACCESS_TOKEN
};

For this to work, we will need to create a new file “contentful.json”, which we’ll place in our root directory. This file will need to hold some configuration.

{
  "CTF_SPACE_ID": "YOURSPACEID",
  "CTF_CDA_ACCESS_TOKEN": "YOURACCESSTOKEN",
  "CTF_ENVIRONMENT": "master"
}

You can find these settings by navigating to > Settings > Api Keys in the Contentful dashboard

When done, save the file and go to the nuxt.config.js

We need to require the newly created config file and add a bit of code to our nuxt.config.js file

// ./nuxt.config.js
const config = require('./.contentful.json')

module.exports = {
  // ...
  env: {
    CTF_SPACE_ID: config.CTF_SPACE_ID,
    CTF_CDA_ACCESS_TOKEN: config.CTF_CDA_ACCESS_TOKEN,
    CTF_ENVIRONMENT: config.CTF_ENVIRONMENT
  }
  // ...
}

The env property is a way to define values that will be available when using process.env when the site is run in a node.js context.

Now that we’ve gotten all the basics setup for using Contentful, next step is to create some content, we can pull into our nuxt application.

Build content in Contentful

Before we can fetch content into the application, we need to create a content-type and some content. Start off by navigating to the tab: Content Model and setup a new content-type

This is image title

Once the content-type is created, we need to add some fields to it.
In this example, we’ll setup a very basic model with the following fields:

This is image title

Next up, we’ll need a few pages. Go ahead and create some pages based on the content-type created. You can do this in the “Content” tab.

This is image title

Awesome — Now we have some content created and we’re ready to do some more work in our code.

Creating the navigation

Our website needs a navigation so our users can navigate between pages. In the “Components” folder, create a new component called “Navigation”

// Navigation.vue
<template>
    <div class="navigation">
      <nav>
        <ul role="menu">
          <li v-for="(navItem, index) in pages" :key="index">
            <nuxt-link :to="'/' + navItem.fields.slug.trim()" role="menuitem">{{navItem.fields.navTitle}}</nuxt-link>
          </li>
        </ul>
      </nav>
    </div>
</template>

<script>
    export default {
        name: 'Navigation',
        props: {
          pages: {
            type: Array, // We expect an array of pages that we need for our navigation
            required: true
          }
        }
    }
</script>

Next, go to the folder “pages” and open up the index.vue file.
In this file we’ll need our navigation component to be included, so we can add it to the file.

//pages/index.vue
<template>
  <section class="container">
    <Navigation :navItems="pages" />
  </section>
</template>

<script>
  import Navigation from '../components/Navigation';
  export default {
    components: {
      Navigation
    }
  }
</script>

As you might notice, in the Navigation.vue, we are passing a prop called navItems with some data that doesn’t exist yet. To pass the pages down to the navigation component, we first need to fetch the data from Contentful

Fetch data from Contentful

First thing we need to do is, import the client from the contentful plugin, we created earlier in the plugins directory:

This is image title

Add the following to the code:

import { createClient } from '../plugins/contentful';
const contentfulClient = createClient();

Next, we need to make use of the asyncData method. This allows us to fetch and render the data server-side. In this we’ll fetch all pages created in Contentful.

Interested in learning more about asyncData: https://nuxtjs.org/api/

//pages/index.vue
asyncData ({env}) {
      return Promise.all([
        // fetch all blog posts sorted by creation date
        contentfulClient.getEntries({
          'content_type': 'page',
          order: '-sys.createdAt'
        })
      ]).then(([pages]) => {
        // return data that should be available
        // in the template
        return {
          navItems: pages.items
        }
      }).catch(console.error)
}

What happens is, we start off by fetching all content created with the content-type of page ordered by date of creation.

When we have the data, we assign it to the property pages, which is also the prop data passed to our navigation component:

Your index.vue file should now resemble something like this:

<template>
  <section class="container">
    <Navigation />
    <div class="container__content">
      <h1>Please select a page you wish to view</h1>
      <p>This is a website for demo purposes of using Nuxt & Contentful together</p>
    </div>
  </section>
</template>
<script>
import Navigation from '../components/Navigation';
import {createClient} from '../plugins/contentful';
const contentfulClient = createClient();
export default {
    components: {
      Navigation
    },
    asyncData ({env}) {
      return Promise.all([
        // fetch all blog posts sorted by creation date
        contentfulClient.getEntries({
          'content_type': 'page',
          order: '-sys.createdAt'
        })
      ]).then(([pages]) => {
        // return data that should be available
        // in the template
        return {
          pages: pages.items
        }
      }).catch(console.error)
    }
  }
</script>

And your page something like this:

This is image title

#nuxtjs #vue #javascript #Contentful

What is GEEK

Buddha Community

How to create a Website using Nuxt.js and Contentful

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

Why Use WordPress? What Can You Do With WordPress?

Can you use WordPress for anything other than blogging? To your surprise, yes. WordPress is more than just a blogging tool, and it has helped thousands of websites and web applications to thrive. The use of WordPress powers around 40% of online projects, and today in our blog, we would visit some amazing uses of WordPress other than blogging.
What Is The Use Of WordPress?

WordPress is the most popular website platform in the world. It is the first choice of businesses that want to set a feature-rich and dynamic Content Management System. So, if you ask what WordPress is used for, the answer is – everything. It is a super-flexible, feature-rich and secure platform that offers everything to build unique websites and applications. Let’s start knowing them:

1. Multiple Websites Under A Single Installation
WordPress Multisite allows you to develop multiple sites from a single WordPress installation. You can download WordPress and start building websites you want to launch under a single server. Literally speaking, you can handle hundreds of sites from one single dashboard, which now needs applause.
It is a highly efficient platform that allows you to easily run several websites under the same login credentials. One of the best things about WordPress is the themes it has to offer. You can simply download them and plugin for various sites and save space on sites without losing their speed.

2. WordPress Social Network
WordPress can be used for high-end projects such as Social Media Network. If you don’t have the money and patience to hire a coder and invest months in building a feature-rich social media site, go for WordPress. It is one of the most amazing uses of WordPress. Its stunning CMS is unbeatable. And you can build sites as good as Facebook or Reddit etc. It can just make the process a lot easier.
To set up a social media network, you would have to download a WordPress Plugin called BuddyPress. It would allow you to connect a community page with ease and would provide all the necessary features of a community or social media. It has direct messaging, activity stream, user groups, extended profiles, and so much more. You just have to download and configure it.
If BuddyPress doesn’t meet all your needs, don’t give up on your dreams. You can try out WP Symposium or PeepSo. There are also several themes you can use to build a social network.

3. Create A Forum For Your Brand’s Community
Communities are very important for your business. They help you stay in constant connection with your users and consumers. And allow you to turn them into a loyal customer base. Meanwhile, there are many good technologies that can be used for building a community page – the good old WordPress is still the best.
It is the best community development technology. If you want to build your online community, you need to consider all the amazing features you get with WordPress. Plugins such as BB Press is an open-source, template-driven PHP/ MySQL forum software. It is very simple and doesn’t hamper the experience of the website.
Other tools such as wpFoRo and Asgaros Forum are equally good for creating a community blog. They are lightweight tools that are easy to manage and integrate with your WordPress site easily. However, there is only one tiny problem; you need to have some technical knowledge to build a WordPress Community blog page.

4. Shortcodes
Since we gave you a problem in the previous section, we would also give you a perfect solution for it. You might not know to code, but you have shortcodes. Shortcodes help you execute functions without having to code. It is an easy way to build an amazing website, add new features, customize plugins easily. They are short lines of code, and rather than memorizing multiple lines; you can have zero technical knowledge and start building a feature-rich website or application.
There are also plugins like Shortcoder, Shortcodes Ultimate, and the Basics available on WordPress that can be used, and you would not even have to remember the shortcodes.

5. Build Online Stores
If you still think about why to use WordPress, use it to build an online store. You can start selling your goods online and start selling. It is an affordable technology that helps you build a feature-rich eCommerce store with WordPress.
WooCommerce is an extension of WordPress and is one of the most used eCommerce solutions. WooCommerce holds a 28% share of the global market and is one of the best ways to set up an online store. It allows you to build user-friendly and professional online stores and has thousands of free and paid extensions. Moreover as an open-source platform, and you don’t have to pay for the license.
Apart from WooCommerce, there are Easy Digital Downloads, iThemes Exchange, Shopify eCommerce plugin, and so much more available.

6. Security Features
WordPress takes security very seriously. It offers tons of external solutions that help you in safeguarding your WordPress site. While there is no way to ensure 100% security, it provides regular updates with security patches and provides several plugins to help with backups, two-factor authorization, and more.
By choosing hosting providers like WP Engine, you can improve the security of the website. It helps in threat detection, manage patching and updates, and internal security audits for the customers, and so much more.

Read More

#use of wordpress #use wordpress for business website #use wordpress for website #what is use of wordpress #why use wordpress #why use wordpress to build a website

Nandini roy

Nandini roy

1618667097

Responsive Personal Portfolio Website Using HTML CSS and JavaScript

Tutorial: https://youtu.be/9DDiorNZiyw

#create a portfolio website with html css javascript #personal portfolio complete website using only html css javascript #responsive portfolio website html css javascript #responsive personal portfolio website #portfolio website #responsive website

anita maity

anita maity

1619013192

Create a Personal Portfolio Website Using HTML CSS and JavaScript

Demo Click Here: https://cutt.ly/2vFKuxe

#portfolio website html css #personal website html css #personal portfolio website #how to create a complete peronal portfolio website #responsive portfolio website html css #responsive personal portfolio website html css

wp codevo

wp codevo

1608042453

How To Create A Complete Responsive Personal Portfolio Website with Just HTML CSS

https://youtu.be/trNdhfJLffg

#how to create a complete personal portfolio website just using html and css #personal website using html #personal portfolio website #portfolio website design using html css javascript