2016-08-08 3 views
0

У меня есть полностью функционирующий прототип новостной карты HTML5, и мне нужно заполнить 50 или около того карт уникальным контентом. Я прошу предложения для более эффективного способа добавления контента на каждую карту, кроме копирования, вырезания и вставки из электронной таблицы Excel. Столбцы таблицы содержат каждую категорию новостей, дату, название и внешний URL. Меня также попросили включить образ из статьи новостей, к которой относится карта, - я не могу представить, как это можно было бы автоматизировать. Этот проект использует стиль Bootstrap, атрибут категории данных на теге в каждой карте и является веб-сайтом Laravel; он не включает Угловые, Усы, Ручки или шаблон шаблонов. Есть ли способ создать пользовательский шаблон для этих новостных карт без необходимости установки механизма фреймворка или шаблона? Могу ли я использовать атрибуты данных?Заполнить шаблоны с содержанием без углового

Вот HTML для одной карты:

<div class="col-lg-4 col-md-6"> 
    <section class="news-box" data-category="blog">    
    <figure> 
     <img src="/material-icons/ic_recent_actors_black_24dp/web/ic_recent_actors_black_24dp_2x.png" class="img-responsive opacity-3"> 
     <figcaption>Blog</figcaption> 
    </figure> 
    <h3 class="h6">Title of Blog Post</h3> 
    <figure> 
     <img src="images/news/pic2.jpg" class="img-responsive"> 
    </figure> 
    <p>luctus et ultrices posuere cubilia Curae; quam erat volutpat. Phasellus dignissim euismod luctus.In leo mauris, blandit quismalesuada lobortis, fringilla a ipsum.</p> 
    </section> 
</div> 

ответ

0

Так что это не может быть лучшим ответом, но это мои 2 цента.

  1. Вы должны сначала преобразовать таблицу Excel в csv, а затем к json объекта. Я думаю, что это можно легко сделать с помощью онлайн-конверторов, таких как: http://www.convertcsv.com/csv-to-json.htm (не пробовал сам, просто вставил первый результат Google). Ваш объект JSON будет выглядеть var foo = [{...},{...},...] (см snipet)

  2. Создать свой «шаблон карты» с фиктивными заполнителей, как card_titlecard_img. Скрыть.

  3. В вашем файле js перебирайте все элементы в объекте json и используйте только что созданный шаблон, чтобы заменить все заполнители. (var newItem = myTemplate.replace('blog_title',val.blog_title)...)

  4. Добавить полученный фрагмент html в контейнер для карточек.

$(document).ready(function(){ 
 
    var template = $(".card-template").html(); //get the card template html 
 
    $.each(foo, function(idx, val){ //iterate over the json object 
 
    var newCard = template.replace('card_title',val.title).replace('card_image',val.img).replace('card_content',val.content); //make a copy of the template and replace the placeholders with the real data 
 
    $(".cards-container").append(newCard); //append the card to the container row 
 
    }); 
 
        
 
    }); 
 

 

 
var foo = [ 
 
    { 
 
    'title':'Gotta catch em all', 
 
    'img':'http://i.imgur.com/tmgWXUP.jpg', 
 
    'content':'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua' 
 
    }, 
 
    { 
 
    'title':'Trumpers trumping Trump', 
 
    'img':'http://i.imgur.com/C7z53mE.gif', 
 
    'content':'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua' 
 
    }, 
 
    { 
 
    'title':'Aint no hacker', 
 
    'img':'http://i.imgur.com/vQGnFD4.jpg', 
 
    'content':'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua' 
 
    } 
 
]
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="row cards-container"> 
 
    <!-- inject cards here --> 
 
</div> 
 

 
<div class="card-template hide"> 
 
    <div class="col-xs-3"> 
 
    <h2>card_title</h2> 
 
    <img src="card_image" class="img-responsive"> 
 
    <p>card_content</p> 
 
    </div> 
 
</div>

Вы также можете попробовать сделать это с ванильным JS, но это до вас.

+0

Это отличное решение JQuery. Для будущих проектов я напишу ту же логику с vanilla JS. Спасибо за ответ. –

0

$(document).ready(function(){ 
 
    var template = $(".card-template").html(); //get the card template html 
 
    $.each(foo, function(idx, val){ //iterate over the json object 
 
    var newCard = template.replace('card_title',val.title).replace('card_image',val.img).replace('card_content',val.content); //make a copy of the template and replace the placeholders with the real data 
 
    $(".cards-container").append(newCard); //append the card to the container row 
 
    }); 
 
        
 
    }); 
 

 

 
var foo = [ 
 
    { 
 
    'title':'Gotta catch em all', 
 
    'img':'http://i.imgur.com/tmgWXUP.jpg', 
 
    'content':'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua' 
 
    }, 
 
    { 
 
    'title':'Trumpers trumping Trump', 
 
    'img':'http://i.imgur.com/C7z53mE.gif', 
 
    'content':'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua' 
 
    }, 
 
    { 
 
    'title':'Aint no hacker', 
 
    'img':'http://i.imgur.com/vQGnFD4.jpg', 
 
    'content':'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua' 
 
    } 
 
]
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="row cards-container"> 
 
    <!-- inject cards here --> 
 
</div> 
 

 
<div class="card-template hide"> 
 
    <div class="col-xs-3"> 
 
    <h2>card_title</h2> 
 
    <img src="card_image" class="img-responsive"> 
 
    <p>card_content</p> 
 
    </div> 
 
</div>