Skip to content

Instantly share code, notes, and snippets.

@artemave
Last active June 11, 2019 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artemave/ba5f262c87db6d8c2f61f0a155f25c44 to your computer and use it in GitHub Desktop.
Save artemave/ba5f262c87db6d8c2f61f0a155f25c44 to your computer and use it in GitHub Desktop.

Super simple jsx server side rendering.

Usage:

  const jsxView = require('./jsxView')

  app.get('/help', handleErrors(async (req, res) => {
    res.type('html')
    res.send(jsxView(process.cwd() + '/views/help.jsx', {supportEmail: 'bob@test.com'))
  }))

view:

const hyperdom = require('hyperdom') // or any jsx factory e.g. React

module.exports.content = ({supportEmail}) => 
<section class="section">
  <h1 class="title">Help &amp; Support<a href="/request-access" class="requestMe button is-danger is-outlined">Request Access</a></h1>
  <div>
    <div class="content">
      <a name="get-in-touch"></a>
      <h2 class="subtitle">Get In Touch</h2>

      <a class="button is-large is-danger is-outlined" href={`mailto:${supportEmail}`}>
        <span>Send us a message</span>
      </a>
    </div>
  </div>
</section>
const vdomToHtml = require('vdom-to-html')
const path = require('path')
const fs = require('fs')
module.exports = function (viewPath, options = {}) {
let vdom
let view = require(viewPath)
if (typeof view == 'function') {
view = view(options)
}
const layoutPath = path.dirname(viewPath) + '/layout.jsx'
if (fs.existsSync(layoutPath)) {
const layout = require(layoutPath)
vdom = layout(view, options)
} else {
vdom = view.content
}
return '<!DOCTYPE html>' + vdomToHtml(vdom)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment