本文整理汇总了Golang中github.com/russross/blackfriday.MarkdownCommon函数的典型用法代码示例。如果您正苦于以下问题:Golang MarkdownCommon函数的具体用法?Golang MarkdownCommon怎么用?Golang MarkdownCommon使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了MarkdownCommon函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: View
func (this *TopicController) View() {
this.Data["IsLogin"] = checkAccount(this.Ctx)
this.Data["IsTopic"] = true
this.TplNames = "topic_view.html"
topic, err := models.GetTopic(this.Ctx.Input.Param("0"))
if err != nil {
beego.Error(err)
this.Redirect("/", 302)
return
}
tid := this.Ctx.Input.Param("0")
this.Data["Tid"] = tid
this.Data["Tag"] = strings.Split(topic.Tag, ",")
topic.Content = string(blackfriday.MarkdownCommon([]byte(topic.Content)))
this.Data["Topic"] = topic
replies, err := models.GetAllReplies(tid)
if err != nil {
beego.Error(err)
return
}
for _, reply := range replies {
unsafe := blackfriday.MarkdownCommon([]byte(reply.Content))
reply.Content = string(bluemonday.UGCPolicy().SanitizeBytes(unsafe))
}
this.Data["Replies"] = replies
this.locale()
}
示例2: testUpdatePost
func testUpdatePost(t *testing.T, title string, markdown string) {
// create JSON payload
var p Post
p.Title = title
p.Markdown = markdown
p.Content = string(blackfriday.MarkdownCommon([]byte(markdown)))
apiPayload, _ := json.Marshal(p)
// save changes to global object for further testing comparison
post.Title = p.Title
post.Content = string(blackfriday.MarkdownCommon([]byte(markdown)))
post.Markdown = markdown
post.Excerpt = excerpt.Make(p.Content, 15)
testUpdatePostAPI(t, apiPayload)
// creates form-encoded payload
p2 := url.Values{}
p2.Set("title", title)
p2.Add("markdown", markdown)
frontendPayload := p2.Encode()
// save changes to global object for further testing comparison
post.Title = p2.Get("title")
post.Markdown = p2.Get("markdown")
post.Excerpt = excerpt.Make(post.Content, 15)
testUpdatePostFrontend(t, frontendPayload)
TestReadPost(t)
}
示例3: DoTopicUpdate
func (m *TopicMgr) DoTopicUpdate(topic *Topic) {
topic.Content = string(blackfriday.MarkdownCommon([]byte(topic.Content)))
reg, _ := regexp.Compile(`\</\w{1,3}\>`)
index := reg.FindAllStringIndex(topic.Content, 8)
x := index[len(index)-1]
topic.Preview = string(blackfriday.MarkdownCommon([]byte(topic.Content[:x[len(x)-1]])))
topic.URL = fmt.Sprintf("/%s/%d.html", topic.CreateTime.Format(helper.Layout_y_m_d), topic.ID)
topic.Time = topic.CreateTime.Format(helper.Layout_y_m_d)
}
示例4: BlogEntry
func BlogEntry(ren render.Render, db *mgo.Database, args martini.Params) {
var result dbBlogEntry
Id, _ := strconv.Atoi(args["Id"])
// Find Blogentry by Id (should be only one)
db.C("blogEntries").Find(bson.M{"id": Id}).One(&result)
fmt.Println(string(blackfriday.MarkdownCommon([]byte(result.Text))))
result.Text = string(blackfriday.MarkdownCommon([]byte(result.Text)))
// render the template using the result from the db
ren.HTML(200, "blogEntry", result)
}
示例5: Get
func (this *MarkTest) Get() {
buf, err := ioutil.ReadFile("view/首页.md")
if err != nil {
}
output := blackfriday.MarkdownCommon(buf)
this.Ctx.WriteByte(output)
}
示例6: visit
func (self *Visitor) visit(path string, f os.FileInfo, err error) error {
if f == nil {
return err
}
if f.IsDir() {
return nil
} else if (f.Mode() & os.ModeSymlink) > 0 {
return nil
} else {
if strings.HasSuffix(f.Name(), ".md") {
fmt.Println(f)
file, err := os.Open(f.Name())
if err != nil {
return err
}
input, _ := ioutil.ReadAll(file)
input = regexp.MustCompile("\\[(.*?)\\]\\(<?(.*?)\\.md>?\\)").ReplaceAll(input, []byte("[$1](<$2.html>)"))
output := blackfriday.MarkdownCommon(input)
var out *os.File
if out, err = os.Create(strings.Replace(f.Name(), ".md", ".html", -1)); err != nil {
fmt.Fprintf(os.Stderr, "Error creating %s: %v", f.Name(), err)
os.Exit(-1)
}
defer out.Close()
if _, err = out.Write(output); err != nil {
fmt.Fprintln(os.Stderr, "Error writing output:", err)
os.Exit(-1)
}
}
}
return nil
}
示例7: articleHandler
func articleHandler(w http.ResponseWriter, req *http.Request) {
uri := req.RequestURI
name := uri[len("/article/"):]
var selected Article
for _, article := range gArticles {
if name == article.name || name+".md" == article.name {
selected = article
}
}
if selected.path == "" {
w.WriteHeader(404)
fmt.Fprintf(w, "Not found")
return
}
data, err := ioutil.ReadFile(selected.path)
if err != nil {
w.WriteHeader(500)
fmt.Fprint(w, err)
return
}
unsafe := blackfriday.MarkdownCommon(data)
html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)
w.Header().Add("Content-Type", "text/html")
w.WriteHeader(200)
w.Write(html)
}
示例8: DescriptionInMarkdown
func (p Property) DescriptionInMarkdown() (template.HTML, error) {
unsafeMarkdown := blackfriday.MarkdownCommon([]byte(p.Description))
safeMarkdown := bluemonday.UGCPolicy().SanitizeBytes(unsafeMarkdown)
// todo sanitized markdown
return template.HTML(safeMarkdown), nil
}
示例9: GetGodos
func GetGodos() []model.Godo {
var godos []model.Godo
// Load all godos from the database
rows, err := db.Query("SELECT ID, Title, Content FROM godo ORDER BY Rank")
if err != nil {
log.Println(err)
}
// Ensure that the database connection is closed
defer rows.Close()
for rows.Next() {
var id int
var title string
var content string
// Fill variables with data from row
if err := rows.Scan(&id, &title, &content); err != nil {
log.Println(err)
}
// Create a Godo from the extracted data
godo := model.Godo{
ID: id,
Title: title,
ContentMD: content,
ContentHTML: template.HTML(string(md.MarkdownCommon([]byte(content))))}
godos = append(godos, godo)
}
return godos
}
示例10: GetBlog
func GetBlog(w http.ResponseWriter, r *http.Request) {
u := User{}
// Check if offset and limit were provided for pagination
vars := mux.Vars(r)
offset, err := strconv.Atoi(vars["offset"])
if err != nil {
// If var is empty assign default value
if strings.ContainsAny(err.Error(), "invalid syntax") {
offset = 0
} else {
log.Printf("No offset query parameter: %s", err)
}
}
limit, err := strconv.Atoi(vars["limit"])
if err != nil {
// If var is empty assign default value
if strings.ContainsAny(err.Error(), "invalid syntax") {
limit = 10
} else {
log.Printf("No offset query parameter: %s", err)
}
}
b, err := selectPageBlogEntries(limit, offset)
if err != nil {
log.Printf("ERROR: could not retrieve blog entries")
}
bFmt := []Post{}
for _, post := range b {
blogpost := Post{
Id: post.Id,
Postdate: post.PostDate.Format("15:04:05 Mon Jan 2 2006"),
Title: post.Title,
Tags: post.Tags,
Body: template.HTML(string(blackfriday.MarkdownCommon([]byte(post.Body)))),
}
bFmt = append(bFmt, blogpost)
}
data := struct {
Blog []Post
User User
}{
bFmt,
u,
}
t, err := template.ParseFiles("tmpl/base.html",
"tmpl/header.tmpl",
"tmpl/navbar.tmpl",
"tmpl/blog-body.tmpl",
"tmpl/footer.tmpl",
"tmpl/js.tmpl")
if err != nil {
log.Printf("ERROR: error creating blog HTML template: %s", err)
}
t.Execute(w, data)
}
示例11: Presentation
//Presentation handles showing page with details about a presentation.
func Presentation(c util.Context) (err error) {
pk, err := datastore.DecodeKey(c.Vars["id"])
if err != nil {
return
}
p, err := presentation.GetByKey(pk, c)
if err != nil {
return
}
as, err := action.GetFor(p, c)
if err != nil {
return
}
a := prepareActions(as)
desc := blackfriday.MarkdownCommon(p.Description)
acts, err := activation.GetForPresentation(pk, c)
if err != nil {
return
}
util.RenderLayout("presentation.html", "Info o prezentácií", struct {
P *presentation.Presentation
A map[string][]time.Time
Desc template.HTML
ZeroTime time.Time
Domain string
Activations []*activation.Activation
Tz *time.Location
}{p, a, template.HTML(desc), time.Date(0001, 01, 01, 00, 00, 00, 00, utc), appengine.DefaultVersionHostname(c), acts, util.Tz}, c, "/static/js/underscore-min.js", "/static/js/presentation.js")
return
}
示例12: Get
// Get Загружает markdown-файл и конвертирует его в HTML
// Возвращает объект типа Post
// Если путь не существует или является каталогом, то возвращаем ошибку
func (p *postArray) Get(md string) (post, int, error) {
info, err := os.Stat(md)
if err != nil {
if os.IsNotExist(err) {
// файл не существует
return post{}, 404, err
}
return post{}, 500, err
}
if info.IsDir() {
// не файл, а папка
return post{}, 404, fmt.Errorf("dir")
}
val, ok := p.Items[md]
if !ok || (ok && val.ModTime != info.ModTime().UnixNano()) {
p.RLock()
defer p.RUnlock()
fileread, _ := ioutil.ReadFile(md)
lines := strings.Split(string(fileread), "\n")
title := string(lines[0])
body := strings.Join(lines[1:len(lines)], "\n")
body = string(blackfriday.MarkdownCommon([]byte(body)))
p.Items[md] = post{title, template.HTML(body), info.ModTime().UnixNano()}
}
post := p.Items[md]
return post, 200, nil
}
示例13: readPageAsHtml
func readPageAsHtml(docName, PageFilePath string) ([]byte, error) {
data, err := ioutil.ReadFile(PageFilePath)
if err != nil {
return nil, err
}
unsafe := blackfriday.MarkdownCommon(data)
// TODO: It could be possible sanitize content before and after
// rendering the wiki-text tags. The post wiki-text sanitising would
// be slightly looser and allow html class attributes.
unsafe = kaufmann.RenderWikiText(docName, unsafe)
p := bluemonday.UGCPolicy()
p.AllowAttrs("class").Matching(bluemonday.SpaceSeparatedTokens).Globally()
// NOTE: At the moment we are allowing anything to be placed in a data attribute.
// We could add a regex to limit the value to valid and safe(!) characters.
// But we will have to write a regex. I can't see any thing suitable in
// the bluemonday code.
// Related: http://stackoverflow.com/q/25897910/395461
p.AllowAttrs("data-pageid").Globally()
p.AllowAttrs("data-filename").Globally()
html := p.SanitizeBytes(unsafe)
return html, nil
}
示例14: readFile
// Reads a file, if the file has the .md extension the contents are parsed and HTML is returned.
func (host *Host) readFile(file string) ([]byte, error) {
stat, err := os.Stat(file)
if err != nil {
return nil, err
}
if stat.IsDir() == false {
fp, _ := os.Open(file)
defer fp.Close()
buf := make([]byte, stat.Size())
_, err := fp.Read(buf)
if err != nil {
return nil, err
}
if strings.HasSuffix(file, ".md") {
return md.MarkdownCommon(buf), nil
} else {
return buf, nil
}
}
return nil, nil
}
示例15: highlight
// `highlight` pipes the source to Pygments, section by section
// delimited by dividerText, then reads back the highlighted output,
// searches for the delimiters and extracts the HTML version of the code
// and documentation for each `Section`
func highlight(source string, sections *list.List) {
language := getLanguage(source)
pygments := exec.Command("pygmentize", "-l", language.name, "-f", "html", "-O", "encoding=utf-8")
pygmentsInput, _ := pygments.StdinPipe()
pygmentsOutput, _ := pygments.StdoutPipe()
// start the process before we start piping data to it
// otherwise the pipe may block
pygments.Start()
for e := sections.Front(); e != nil; e = e.Next() {
pygmentsInput.Write(e.Value.(*Section).codeText)
if e.Next() != nil {
io.WriteString(pygmentsInput, language.dividerText)
}
}
pygmentsInput.Close()
buf := new(bytes.Buffer)
io.Copy(buf, pygmentsOutput)
output := buf.Bytes()
output = bytes.Replace(output, []byte(highlightStart), nil, -1)
output = bytes.Replace(output, []byte(highlightEnd), nil, -1)
for e := sections.Front(); e != nil; e = e.Next() {
index := language.dividerHTML.FindIndex(output)
if index == nil {
index = []int{len(output), len(output)}
}
fragment := output[0:index[0]]
output = output[index[1]:]
e.Value.(*Section).CodeHTML = bytes.Join([][]byte{[]byte(highlightStart), []byte(highlightEnd)}, fragment)
e.Value.(*Section).DocsHTML = blackfriday.MarkdownCommon(e.Value.(*Section).docsText)
}
}