Adding Search Functionality
<!--templates/search.html--> {% extends "base.html" %} {% block head %} {{ super() }} <script src="/static/scripts/search.js"></script> <link href="/static/styles/search.css" rel="stylesheet"> {% endblock %} {% block ad %} <div class="ad region"> <img src="/static/images/ad.jpg" /> </div> <div style="clear: both;"></div> {% endblock %} {% block content %} <div id='content'> <h2 class="search-title">លទ្ធផលនៃការស្វែងរកៈ</h2> {% if 'q' in data %} <script> search.q = '{{ data["q"] }}'; gapi.load('client', initAPI); </script> {% endif %} <ul id="search-result"></ul> </div> {% endblock %}
//static/scritps/search.js class Search{ constructor(){ this.pageToken = false; this.apiKey = 'AIzaSyCDMr6toQGyDRFPChRsbQ2sheSQfTQLVqg'; this.blogId = '3212243556817590089'; this.q = false; } makeApiCall(){ gapi.client.load('blogger', 'v3', function(){ var q = search.q ? 'q='+search.q+'&':''; var postBody = 'fetchBodies=false&' var myPageToken = search.pageToken ? 'pageToken='+search.pageToken:''; var blogId = search.blogId; var requestPath = 'https://www.googleapis.com/blogger/v3/blogs/'+blogId+'/posts/search?'+ q + postBody + myPageToken; var request = gapi.client.request({ 'path': requestPath , }); request.execute(function(response) { /////////////////////////////////////// search.getPostAPI(response); /////////////////////////////////////// }); }); } createThumb(postContent){ var div = document.createElement( 'div' ); div.innerHTML = postContent; var img = div.getElementsByTagName("img"); if(img.length>=1) { return img[0].src; } else{ return ("/static/images/no-image.png"); } } getPostAPI(json){ this.postTitle = []; this.postId = []; this.totalPost = json.items.length; search.pageToken = json.nextPageToken; this.postList = json.items; this.startIndex = 1; for(var i =0; i<this.postList.length; i++){ this.postTitle.push(this.postList[i].title); this.postId.push(this.postList[i].id); } search.listingPosts(); } listingPosts(){ var html = ''; for(var v in search['postId']) html += `<li><a href="/post/${search.postId[v]}/">${search.postTitle[v]}</a></li>`; $('#search-result').append(html); } }//end class const search = new Search(); function initAPI() { gapi.client.setApiKey(search.apiKey); search.makeApiCall(); }
/* static/styles/search.css */ .ad{ padding:0; } .ad img{ width: 100%; margin: 20px 0 0; float: left; } #content{ background: lavender; padding: 20px; } #content .search-title{ font: 22px/1.5 Oswald, Limonf3; margin-bottom: 20px; } #content ul{ list-style-position: inside; } #content ul li{ padding: 5px 0; } #content ul li a{ font-size: 15px; color: #014c72; padding: 10px; } #content #load-more{ margin-top: 20px; text-align: center; } #content #load-more img:hover{ opacity: .5; cursor: pointer; }
GitHub: "https://github.com/Sokhavuth/newspaper
Heroku: https://khmerweb-newspaper.herokuapp.com/
Comments
Post a Comment