Blog

Blog

PHODAL

markdown angular,网站重构四,angularjs insert html

因为再有的博客基本上是用markdown写的,所以需要将markdown写的博客转为html,再丢给angular处理。

Markdown

Markdown 是一种轻量级标记语言,创始人为约翰·格鲁伯(John Gruber)和亚伦·斯沃茨(Aaron Swartz)。它允许人们“使用易读易写的纯文本格式编写文档,然后转换成有效的XHTML(或者HTML)文档”。这种语言吸收了很多在电子邮件中已有的纯文本标记的特性。

安装markdown js

npm install markdown

简单的用法就是如下面

var markdown = require( "markdown" ).markdown;
console.log( markdown.toHTML( "Hello *World*!" ) );

所以我们要做的就是,声明下markdown,再添加到app.js中

content:markdown.toHTML(row.content),

代码中添加了一个新的元素用于获取最后的十个博客,用的是underscore为的是以后方便,所以最后的app.js代码如下所示


var restify = require('restify');
var _ = require('underscore')._;
var sqlite3 = require('sqlite3').verbose();
var markdown = require( "markdown" ).markdown;

var db = new sqlite3.Database('sqlite3.db');

var server = restify.createServer(); var content = new Array();

server.use( function crossOrigin(req,res,next){ res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); return next(); } );

db.all("SELECT id,content,title,description,slug,created,updated,publish_date,keywords_string FROM blog_blogpost", function(err, rows) { rows.forEach(function (row) { content.push({ id:row.id, slug:row.slug, description:row.description, title:row.title, content:markdown.toHTML(row.content), keywords:row.keywords_string, created:row.created, updated:row.updated, publish_date:row.publish_date }); }); function respond(req,res,next){ var data = content[req.params.name-1]; res.json(data, {'content-type': 'application/json; charset=utf-8'}); } function all(req,res,next){ var data = {blogposts_sum:rows.length}; res.json(data, {'content-type': 'application/json; charset=utf-8'}); }
function respages(req,res,next){ var data = _.last(content,10); data = data.reverse(); res.json(data, {'content-type': 'application/json; charset=utf-8'});
} server.get ('/blog',all); server.get ('/blog/page/:page',respages); server.head ('/blog/page/:page',respages); server.get ('/blog/:name',respond); server.head ('/blog/:name',respond); db.close(); });

server.listen(10086, function() { console.log('%s listening at %s', server.name, server.url); });

Angularsjs 插入html

ng-bind-html

这个指令要引入sanitize 模块

这里似乎需要用到trustAsHtml()这个神奇的东东,看看官方是怎样示例的 $sanitize

The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are then serialized back to properly escaped html string. This means that no unsafe input can make it into the returned string, however, since our parser is more strict than a typical browser parser, it's possible that some obscure input, which would be recognized as valid HTML by a browser, won't make it through the sanitizer.

看代码:


function Ctrl($scope, $sce) {
    $scope.snippet =
      '

an html\n' + 'click here\n' + 'snippet

'; $scope.deliberatelyTrustDangerousSnippet = function() { return $sce.trustAsHtml($scope.snippet); }; }

以及HTML部分

     <pre><div ng-bind-html="deliberatelyTrustDangerousSnippet()">

整合

index.html部分

<!doctype html>
<html lang="en" ng-app="blogposts">
<head>
  <meta charset="utf-8">
  <title>Phodal's New Homepage</title>
  <script src="js/angular.min.js"></script>
  <script src="js/app.js"></script>
</head>
<body ng-controller="postlistCtrl">

  <div class="container-fluid">
    <div class="row-fluid">
      <div class="span10">
        <ul class="posts">
          <article ng-repeat="post in posts">
            <h1>{{post.title}}</h1>
            <p>{{post.description}}</p>
          </article>
        <article>
          <div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div>
        </article>
        </ul>
      </div>
    </div>
  </div>
</body>
</html>

app.js部分


  var blogposts = angular.module('blogposts', []);

  blogposts.controller('postlistCtrl', function($scope, $http, $sce) {
      $http.get('http://0.0.0.0:10086/blog/page/1').success(function(data) {
          $scope.posts = data;
      });
      $http.get('http://0.0.0.0:10086/blog/1').success(function(data) {
          $scope.post1 = data;
          console.log(data.content);
          $scope.deliberatelyTrustDangerousSnippet = function() {
            return $sce.trustAsHtml(data.content);
          };
      });
  });

或许您还需要下面的文章:

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签