如何访问树枝中的特定索引?

时间:2015-12-15 23:53:13

标签: symfony twig

我正在尝试从我的对象中获取特定值。我只想在其中打印第一个元素,所以我尝试通过在数组位置访问它来将其视为数组。

我也尝试过使用twig属性函数

但是我无法让它发挥作用。

var mongo = require('mongodb');

var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('drinkdb', server);

db.open(function(err, db) {
    if(!err) {
        console.log("Connected to 'drinkdb' database");
        db.collection('drinks', {strict:true}, function(err, collection) {
            if (err) {
            console.log("The 'drinks' collection doesn't exist. Creating it with sample data...");
            populateDB();
            }
        });
    }
    });

exports.findById = function(req, res) {
    var id = req.params.id;
    console.log('Retrieving drink: ' + id);
    db.collection('drinks', function(err, collection) {
        collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
            res.send(item);
        });
    });
};

exports.findAll = function(req, res) {
    db.collection('drinks', function(err, collection) {
        collection.find().toArray(function(err, items) {
            res.send(items);
        });
    });
};

exports.addDrink = function(req, res) {
    var drink = req.body;
    console.log('Adding drink: ' + JSON.stringify(drink));
    db.collection('drinks', function(err, collection) {
        collection.insert(drink, {safe:true}, function(err, result) {
            if (err) {
            res.send({'error':'An error has occurred'});
            } else {
            console.log('Success: ' + JSON.stringify(result[0]));
            res.send(result[0]);
            }
        });
    });
};

exports.updateDrink = function(req, res) {
    var id = req.params.id;
    var drink = req.body;
    console.log('Updating drink: ' + id);
    console.log(JSON.stringify(drink));
    db.collection('drinks', function(err, collection) {
        collection.update({'_id':new BSON.ObjectID(id)}, drink, {safe:true}, function(err, result) {
            if (err) {
                console.log('Error updating drink: ' + err);
                res.send({'error':'An error has occurred'});
            } else {
                console.log('' + result + ' document(s) updated');
                res.send(drink);
            }
        });
    });
};

exports.deleteDrink = function(req, res) {
    var id = req.params.id;
    console.log('Deleting drink: ' + id);
    db.collection('drinks', function(err, collection) {
        collection.remove({'_id':new BSON.ObjectID(id)}, {safe:true}, function(err, result) {
            if (err) {
            res.send({'error':'An error has occurred - ' + err});
            } else {
            console.log('' + result + ' document(s) deleted');
            res.send(req.body);
            }
        });
    });
};

/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
// You'd typically not find this code in a real-life app, since the database would already exist.
var populateDB = function() {

    var drinks = [{
        id: "1",
        name: "Margarita",
        //ingredients: ["Tequila","Lime juice","Triple Sec","Lime","Salt","Ice"],
        //measurements: ["2 oz","1 oz","1 oz","1","optional","optional"],
        directions: "Shake the other ingredients with ice, then carefully pour into the glass. Served: On the rocks; poured over ice. Optional: Salt the rim of the glass by rubbing lime on it so it sticks."
    },{
        id: "2",
        name: "Strawberry Margarita",
        //ingredients: ["Tequila", "Lime juice","Triple Sec","Strawberries","Lime","Salt", "Ice"],
        //measurements: ["2 oz","1 oz", "1 oz", "3 1/2 cups", "1", "optional", "optional"],
        directions: "Combine strawberries, ice, tequila, lime juice, and triple sec in a blender, and process until the mixture is smooth. Carefully pour into the glass. Served: On the rocks; poured over ice. Optional: Salt the rim of the glass by rubbing lime on it so it sticks."
    }];

    db.collection('drinks', function(err, collection) {
        collection.insert(drinks, {safe:true}, function(err, result) {});
    });
};

我试过{{t.name | first}}但它只返回循环中每个项目的第一个字母。

bet.orm.yml

{% for b in dotabets %}    
    {% for t in b.teams %}
       You bet on: {{ t.name[0] }}
    {% endfor %}
{% endfor %}

控制器

AppBundle\Entity\Bet:
type: entity
repositoryClass: AppBundle\Entity\Repository\BetRepository
table: bets
id:
    id:
        type: integer
        id: true
        generator:
            strategy: AUTO
fields:
    createdDatetime:
        type: datetime
        column: created_datetime
    betTime:
        type: datetime
        column: bet_time
    status:
        type: integer
        length: 2
    result:
        type: integer
        length: 2
        nullable: true
    homeOdds:
        type: decimal
        scale: 2
    awayOdds:
        type: decimal
        scale: 2
    closedDatetime:
        type: datetime
        column: closed_datetime
        nullable: true
manyToOne:
    game:
        targetEntity: AppBundle\Entity\Game
manyToMany:
    teams:
        targetEntity: AppBundle\Entity\Team
        joinTable:
            name: bets_teams
            joinColumns:
                bet_id:
                    referencedColumnName: id
            inverseJoinColumns:
                team_id:
                    referencedColumnName: id

1 个答案:

答案 0 :(得分:2)

要在树枝上访问数组中的第一个对象,您可以使用“第一个”#39;树枝过滤器本身:

请参阅the Twig documentation about first

基本上你做的是:

{{ name }}

访问数组的第一个值。

你的例子不会起作用,因为{{ b.teams[0].name }} 没有被定义为变量。如果它包含在团队中,那么你应该这样做:

restify.CORS()

假设您想要集合中第一个团队的名称,索引从0开始