Example #1
0
// CategoryView shows a list of posts arranged by its category
func CategoryView(c *echo.Context) error {
	// Parse pagination attributes
	pn, ps := utils.GetPage(c)
	id, _ := strconv.Atoi(c.Param("id"))

	// Get category using id
	var category models.Category
	err := database.Current.Get(&category, database.Queries.CategoryByID, id)
	if err != nil {
		log.Println("Cannot select category:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Query the posts
	var posts []models.AuthoredPost
	err = database.Current.Select(&posts, database.Queries.AuthoredPostsByCategory, id, ps, ps*(pn-1))
	if err != nil {
		log.Println("Cannot select posts:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	var count int
	err = database.Current.Get(&count, database.Queries.PostByCategoryCount, id)
	if err != nil {
		log.Println("Cannot count posts:", err)
	}

	pc := int(math.Floor(float64(count/ps))) + 1

	// Generate preview for all posts
	for _, p := range posts {
		p.Preview = createPreview(p.TextContent)
	}

	// Create our context and fill base data
	cc := categoryContext{
		Category: category,
		RelatedPosts: models.Paginated{
			TotalObjects:  count,
			PageCount:     pc,
			PageNumber:    pn,
			PageSize:      ps,
			NextAvailable: pn < pc,
			Results:       posts,
		},
	}

	err = fillBlogContext(c, &cc.blogContext)
	if err != nil {
		log.Println("Cannot fill blog context", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Render the results
	return c.Render(200, "category", cc)
}
Example #2
0
// Index serves blog index view
func Index(c *echo.Context) error {

	// Parse pagination attributes
	pn, ps := utils.GetPage(c)

	// Query the posts
	var posts []models.AuthoredPost
	err := database.Current.Select(&posts, database.Queries.AuthoredPosts, ps, ps*(pn-1))
	if err != nil {
		log.Println("Cannot select posts:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	var count int
	err = database.Current.Get(&count, database.Queries.PostCount)
	if err != nil {
		log.Println("Cannot count posts:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	pc := int(math.Floor(float64(count/ps))) + 1

	// Generate preview for all posts
	for _, p := range posts {
		p.Preview = createPreview(p.TextContent)
	}

	// Create our render context and fill base data
	ic := indexContext{
		PostResults: models.Paginated{
			TotalObjects:  count,
			PageCount:     pc,
			PageNumber:    pn,
			PageSize:      ps,
			NextAvailable: pn < pc,
			Results:       posts,
		},
	}

	err = fillBlogContext(c, &ic.blogContext)
	if err != nil {
		log.Println("Cannot fill blog context", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Render the results
	return c.Render(200, "index", ic)
}